Learning Kotlin: Java To Kotlin Converter

Submitted by Robert MacLean on Wed, 06/13/2018 - 09:00

More Information

The second Koan is meant as an exercise of the IDE and is targetted 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?

Java
  1. package i_introduction._1_Java_To_Kotlin_Converter;
  2.  
  3. import util.JavaCode;
  4.  
  5. import java.util.Collection;
  6. import java.util.Iterator;
  7.  
  8. public class JavaCode1 extends JavaCode {
  9.     public String task1(Collection<Integer> collection) {
  10.         StringBuilder sb = new StringBuilder();
  11.         sb.append("{");
  12.         Iterator<Integer> iterator = collection.iterator();
  13.         while (iterator.hasNext()) {
  14.             Integer element = iterator.next();
  15.             sb.append(element);
  16.             if (iterator.hasNext()) {
  17.                 sb.append(", ");
  18.             }
  19.         }
  20.         sb.append("}");
  21.         return sb.toString();
  22.     }
  23. }
  24.                    
Kotlin
  1. package i_introduction._1_Java_To_Kotlin_Converter;
  2.  
  3. import util.JavaCode;
  4.  
  5. import kotlin.collections.Collection;
  6.  
  7.  class JavaCode1 : JavaCode() {
  8.     fun task1(collection : Collection<Int>) : String {
  9.         val sb = StringBuilder()
  10.         sb.append("{")
  11.         val iterator = collection.iterator()
  12.         while (iterator.hasNext()) {
  13.             val element = iterator.next()
  14.             sb.append(element)
  15.             if (iterator.hasNext()) {
  16.                 sb.append(", ")
  17.             }
  18.         }
  19.         sb.append("}")
  20.         return sb.toString()
  21.     }
  22.  }
  23.                        

The first thing you'll notice is that the java.util.Collection is gone since Kotlin has its' own implementation and it is imported by default.

Next is the lack of Visibility Modifiers in the code. This is because everything is public by default. In addition to public there are protected, private and internal which work the same as with .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.