Learning Kotlin: Java To Kotlin Converter

The second koan is meant as an exercise of the IDE and is targeted at those moving from Java; as such, it 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—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 collection) {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        Iterator 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 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 as .NET’s 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 in Java or C#) without issue, but you don’t need them unless the compiler needs clarity.