Kotlin: An Introduction

- Raffael Schneider

Kotlin is a cross-plattform, statically typed general-purpose programming language. Since its very inception, it was conceived as fully interoperable with Java and its JVM. Kotlin was developed by the Czech software company JetBrains, the makers of the well-known IntellJ IDE. By 2019 Google officially announced Kotlin, to be its preferred language for Android app development. In summary, the main idea of Kotlin is to improve upon Java in order to make up a better programming experience overall.

  • Footprint: the generated bytecode has been improved as much over time to be as small as Javas
  • Interoperability: fully interoperable with Java making it possible to code in Kotlin alongside Java classes in legacy Java projects
  • Scalability: Coroutines makes it possible to write server-side applications without losing out on scalability
  • Learning-curve: By building upon Java rather than replacing it, learning Kotlin feels more like learning an upgrade
  • Readability: Syntactic sugars and many small improvements reduce boilerplate code and thus make up for concise codebase (1)

Kotlin is not only meant for Android development: With the announcement of the new release version of Spring Framework 5 earlier in 2017, Kotlin is also officially supported by a popular framework which boasts a large business userbase. (2)

And that's how Kotlin looks like

Before we jump into real-world Kotlin code, let's have a look at a very basic not-so-uncommon occurence of a Java class. Its method callIfMatch() takes a string as a parameter, and because the string might be null, let's call it "nullableString". The very first thing the method does is to write the content of nullableString to the log output, but we check it for the possibility of being null in order to be null-safe. Right after that, we check again (!) if nullableString is null and if not contains a certain string pattern to match to. If the check passes, we call method call(). So to sum it up, we got a method callIfMatch() and what matters to us the most here is the way we handle null-safety in a very explicit manner.

public void callIfMatch(String nullableString) {
    Log.callerClass("callerClass", nullableString != null ? nullableString, "defaultString");    

    if (nullableString != null && nullableString.contains("matchMe"){
        call();
    }
}

Here we got the equivalent snippet of code written in Kotlin. We notice right away that we needed less characters to write the same business logic. The method callIfMatch() also takes a string object that we called nullableString. A difference you might understand quite intuitively is that the type of the parameter is declared after the very name and after its following colon character. We're also introtuced to a new syntactic character: the question mark. The question mark denotes the possibility of nullableString to actually be null. That's how the compiler knows in advance right at the moment wenn the variable nullableString is being declared that it might be null during runtime. Furthermore, everytime we use said variable nullableString, we can add ? and make sure that the null-check happens at the very same time we use the variable for something else. We call that implicit null-safety. The actual outcome is exactly the same as in Java class above.

fun callIfMatch(nullableString: String?) {
    Log.callerClass("callerClass", nullableString ?: "defaultString")

    when(nullableString?.contains("matchMe")){
        true -> { call() }
    }
}

Here we got another very typical use of Java. The method showStatusText() returns various text depending what type class someState is being instanced by. There are 3 different possibilities: Conntected, Connecting and Disconnected. We use a basic if-else loop to make the checks on all three possibilities. At the end of the method, a return string is being built with whatever instance someState was in. So far so good.

public String showStatusText() {
    String text = null;

    // Expecting only 3 different states
    if (someState instanceOf Connected) {
        text = "Client connected.";
    } else if (someState instanceOf Connecting){
        text = "Connecting..."
    } else if (someState instanceOf Disconnected){
        text = "Not Connected."
    }

    return "Status: " + text + " Please take note!"
}

As before, we can notice right away how much leaner and more elegant equivalent code looks like in Kotlin. The main difference here is the way we check whether instance someState is being declared in. We use the keywords when and is in order to make the type class check. Furthemore, when you look at the way the return string is being built together, we see that the mere use of a $ followed by the variable makes sure to insert, or rather concate, the appropriate string. Very hand if you ask me.

fun showStatusText() {
    val text = when(someState) {
        is Connected -> "Client connected."
        is Connecting -> "Connecting..."
        is Disconnected -> "Not Connected."
    }

    return "Status: $text Please take note!"
}

With those two examples, we can hopefully see how Kotlin may very well improve the cleanness of your codebase by syntactic benefits in comparison to Java.

Try it out for yourself

If we succeded to make you curious enough to try out the Kotlin programming language for yourself, there is a variety of tools available for doing so. As a first step, we recommend you to head to their web implemented interpreter platform called Kotlin Playground:

Kotlin Playground

If that's not enough, another official tool to use right from within your web browser is their online editor where you get access to the whole standard library:

Try Kotlin

Furthermore, last year in December 2019 KotlinConf opened its doors in Copenhague, the worlds largest Kotlin conference showcasing the latest developments regarding the programming language. Make sure to check out their talks and listen to what the developers themselves have to say about it. You can find the conferences website in the links just below.

Links and references

Official Kotlin website

Official tutorial series

Baeldung course for Kotlin

Introduction to Kotlin (Google I/O '17') von Andrey Breslav (Kotlin Lead-Entwickler)

KotlinConf Copenhague 4-6 Dec 2019