After doing the first tutorial on Kotlin, I was impressed, but let’s face it, anyone can do a simple “hello world” style program. Nevertheless, I decided to continue with the Kotlin tutorial found at kotlinlang.org. When I moved onto part two of the tutorial, I was really impressed.
It wasn’t that I was super impressed with the language itself. It was IntelliJ’s support of Kotlin that blew me away. When you copy and paste Java code into the IDE, it will offer to translate it to Kotlin for you.
You can see in the video that IntelliJ just did the work of taking the Java code that I copied and pasted into my Kotlin class. I thought this was incredibly slick because it gave me the change to see the differences between Java and Kotlin.
Of course, I wanted to do the exercise myself so that I can get the hang of writing Kotlin code. The problem in this portion of the tutorial was to take this Java code and rewrite as Kotlin code.
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(); } }
It’s not too painful of code. Here is what I ended with when I wrote the code as Kotlin code on my own.
fun todoTask1(collection: Collection): Nothing = TODO( """ Task 1. Rewrite JavaCode1.task1 in Kotlin. In IntelliJ IDEA, you can just copy-paste the code and agree to automatically convert it to Kotlin, but only for this task! """, references = { JavaCode1().task1(collection) }) fun task1(collection: Collection): 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() }
There was one thing I noticed about the Kotlin code that I liked. It looks as if we are allowed to have free standing functions in Kotlin outside of a class definition. While I appreciate OOP, there are frankly times where I’m not sure if OOP is the best approach to a problem. This was one of things I really like about Python is that I can break out of OOP when I want.
Now I know that it’s perfectly true that we can use static imports in Java, but I have always felt that was a clumsy approach. Static functions and static imports always seemed more like an after thought to the language that got tacked on after enough people complained. Of course, that’s just a matter of opinion, but anyway, I do like having a choice in Kotlin about when to use classes or just when to use function. Kotlin seems to have included this choice as part of the design of the language right from the get go.
One thought on “Kotlin Koans—Part 2”