The second Koan is meant as an exercise of the IDE and is targeted at those moving from Java, as such this was a mixed bag for me.
The goal is to get a Kotlin version of Java code by letting the IDE do the conversion, but I decided to tackle it myself.
Initially, I thought I needed to do the entire file and not just the task function. So, what does the entire code look like when changed?
package i_introduction._1_Java_To_Kotlin_Converter;
import util.JavaCode;
import java.util.Collection;
import java.util.Iterator;
public class JavaCode1 extends JavaCode {
public String task1(Collection<Integer> collection) {
StringBuilder sb = new StringBuilder();
sb.append("{");
Iterator<Integer> iterator = collection.iterator();
while (iterator.hasNext()) {
Integer element = iterator.next();
sb.append(element);
if (iterator.hasNext()) {
sb.append(", ");
}
}
sb.append("}");
return sb.toString();
}
}
package i_introduction._1_Java_To_Kotlin_Converter;
import util.JavaCode;
import kotlin.collections.Collection;
class JavaCode1 : JavaCode() {
fun task1(collection : Collection<Int>) : String {
val sb = StringBuilder()
sb.append("{")
val iterator = collection.iterator()
while (iterator.hasNext()) {
val element = iterator.next()
sb.append(element)
if (iterator.hasNext()) {
sb.append(", ")
}
}
sb.append("}")
return sb.toString()
}
}
The first thing you’ll notice is that the java.util.Collection
is gone since Kotlin has its’ own implementation and is imported by default.
Next is the code’s lack of Visibility Modifiers. This is because everything is public by default. In addition to public there are protected, private and internal which work the same .NETs modifiers.
The next change is the variables, you don’t need to define the type before the variable… you just define val for read-only variables or var for mutable variables. This is similar to C#s var keyword.
The final change is the lack of semicolons. This doesn’t mean Kotlin doesn’t have them, it means they are optional. You can add them as if it was Java or C# with no issue, it is you don’t need them unless you are doing something confusing for the compiler.