Farewell Java, Welcome Kotlin

Since the Google I/O and unveiling of the new official language of Android I devoted quite a bit of time to getting to know it. Over the several dozen hours I spent with Kotlin over this time I came to realise my deep hate for Java. There is simply so much wrong with this language that it is really refreshing to finally be able to code in a language that get things right. I know I’ve already written about it but I guess Kotlin will be a recurring topic on this blog over the next few months so buckle up.

New module for Linux Session’s app

In the last entry I posted about the project I complained about not being able to properly setup Gradle for Kotlin. Soon after uploading that post though, I managed to fix it and I started working on another module for the project. Photo Booth is a thing I wanted to see on every single conference I attended. The basic premise is that users can take photos at the event which would then be approved by an administrator. After that they would be uploaded to a server and displayed as a common gallery for all users. I believe it to be quite an amazing tool for networking and getting people to actually use the application.

As you can see on Github I’ve decided to write this module in plain Kotlin to test the interop between Java and Kotlin. So far I found no problems so Google delivered :). The learning curve isn’t that steep and I think I’m already faster with Kotlin than I’ve ever been with Java. I’ve only implemented about half of the logic and views behind the module but I already see that the code volume will decrease by about 30-40% compared to Java. It is amazing how concise and elegant Kotlin is.

The best bits (so far)

The days of NullPointerExceptions are over! Kotlin claims to be a great step towards null-safety and it is. The only way to get an NPE is to actually scream at the compiler to give you one. Really, only nullable!!.member throws NPE if nullable is null. The idiomatic ways of dealing with optional values are really elegant and straightforward. In the three samples I will present how much boilerplate can be reduced using Kotlin when it comes to null-safety and casting:

//-----1----- Safe Calls
//Java
(bob != null && bob.department != null && bob.department.head != null) ? bob.department.head.name : null
//Kotlin
bob?.department?.head?.name

//-----2----- Elvis Operator
//Java
OnClickListener l = (presenter != null) ? presenter.listener : new MyListener()
//Kotlin
val l = presenter?.listener ?: MyListener()

//-----3----- Smart Casting
//Java
if (x instanceof String && ((String) x).length > 0)
    System.out.print(((String) x).length)
//Kotlin
if (x is String && x.length > 0)
    print(x.length)

When and other expressions

Java’s selective switch has been exchanged for something much better. When can be used with any type and with much more than simple value check. Let the code speak for itself though:

//-----4-----
when (x) {
    0, 1 -> print("x == 0 or x == 1")
    else -> print("otherwise")
}

//-----5----- 'cases' don't have to be simple values
when (x) {
    contains(s) -> print("x contains s")
    else -> print("x doesn't contain s")
}

//-----6----- can be used with ranges
when (x) {
    in 1..10 -> print("x is in the range")
    in validNumbers -> print("x is valid")
    !in 10..20 -> print("x is outside the range")
    else -> print("x is weird")
}

//-----7----- can be used to check type
when (x) {
    is Foo -> ...
    is Bar -> ...
    else   -> ...
}

//-----8----- with no argument can stand for if-else if-else chain
when {
    x.isOdd() -> print("x is odd")
    x.isEven() -> print("x is even")
    else -> print("x is funny")
}

On top of that when, if and try are expressions so they can be used as such:

//-----9-----
fun transform(color: String): Int {
    return when (color) {
        "Red" -> 0
        "Green" -> 1
        "Blue" -> 2
        else -> throw IllegalArgumentException("Invalid color param value")
    }
}

//-----10-----
val result = try {
        count()
    } catch (e: ArithmeticException) {
        throw IllegalStateException(e)
}

//-----11-----
val result = if (param == 1) {
        "one"
    } else if (param == 2) {
        "two"
    } else {
        "three"
}

The todo list

Except for the great stuff listed above I am really looking forward to using some other features of Kotlin language in some future modules I will write for the project. The stuff listed below is my current to-learn list of topics I have some knowledge of but want to know more.

– Anko – amazing library of shorthands and utility functions for Kotlin
– Anko’s DSL – Now it is possible to create an Android application without using xml’s. Anko’s layouts provide great functionality to declare views concisely and efficiently directly in Kotlin code. I really need to look more into it as it seems really unreasonably great.
– Type Aliases – I have started a new project at my job using Kotlin and I’m trying to develop an easy to use, understandable, concise system of creating proper, safe, modular MVP architecture in Kotlin using Type Aliases. The goal is to change BaseMvpPresenter<ParkingContract.View> into ParkingP. I still have some open questions and work ahead of me. But I really want to focus on it some more in the next week.

I am really grateful for Kotlin but I still have a lot to learn before I can say I’m fluent with it. I will keep you updated and I recommend you try it on your own. Until then, stay curious.

4 Comments

  1. Radoslaw Maruszewski 2017-05-31 at 11:50

    Kotlin is a poor man’s Scala. 😉 And making classes final by default was a terrible decision, you can say goodbye to test doubles.

    1. Julian Jurec 2017-05-31 at 14:37

      Kotlin might be a poor man’s Scala but it is still definitely better than Java and unfortunately you cannot use Scala to code for Android. Besides, it is still a well designed language in itself as far as I’m concerned. Please, prove me wrong though.

      1. Radoslaw Maruszewski 2017-06-02 at 09:55

        I did, didn’t I? 😉 Try to write a unit test while mocking your Kotlin classes, and you’ll see what I mean. It’s really unfortunate, because Kotlin is a nice language. It’s creators, probably blindly following Josh Bloch’s advice “Design and document for inheritance or else prohibit it”, have made one (big) mistake, which hinders its wider adoption.

        Now, Java is not that terrible. It’s just a bit outdated and backward compatible. The code you’ve created using Java 1.2 is guaranteed to compile in run in Java 12 without much problems. Which in turn means that all these Hashtables, StringBuffers, Enumerations, clones and nulls are to stay there forever. Other languages don’t care so much about backward compatibility. In fact, I have talked with one of the creators of Kotlin, and she told me that they still consider changing these “final” classes to “non-final” in the next Kotlin version, or even making this functionality configurable.

        It’s great, because it means that Kotlin may become a really great language one day. But it’s also the very reason that Java will be here in 20 years, while Kotlin will be (most probably) long forgotten. Or replaced with something more shiny. 🙂

        1. Julian Jurec 2017-06-05 at 20:27

          “have made one (big) mistake, which hinders its wider adoption” – would you care to elaborate on that? I’m afraid I didn’t exactly get which one mistake you mean.

          Also, thank you very much for your input. I am really glad you took time to write this comment and to explain to me your thoughts. I always love to hear from people more experienced and knowledgeable than myself and I appreciate every discussion.

Leave a Reply to Julian Jurec Cancel reply

Your email address will not be published. Required fields are marked *