Practically on the go with Kotlin

13.12.2019 Raffael Schneider
Tech kotlin jvm foss handson goodtoknow

Kotlin is a cross-platform, statically typed programming language. From the beginning, Kotlin was geared towards being completely interoperable with Java and its JVM. Kotlin was developed by the multinational software company JetBrains, the makers of the established IDE IntelliJ. In 2019, Google declared Kotlin as the official developer language (preferred language) for Android app development. Using today's development knowledge in programming languages, to offer a more comfortable and pragmatic alternative to Java that remains 100% compatible with the previous Java ecosystem.

Here is a small list of all the advantages that Kotlin has over Java and similar languages:

  • Smaller footprint Kotlin’s compiler generates bytecode of similar size compared to Java
  • Interoperability Thanks to full compatibility with the Java stack, Kotlin classes can be written and maintained together with Java classes in one project
  • Scalability Kotlin has native coordination and thus allows the development of scalable solutions
  • Learning curve: Although Kotlin has a slightly different syntax, keywords and functionalities, the jump from Java to Kotlin is quite feasible for everyone thanks to intuitive design features
  • Readability / maintainability Syntactic sugar and other language properties make the code more manageable and thus more maintainable
  • Not only for Android: Through native support of Spring Framework 5 <a href="https://spring.io/blog/2017/01/04/introducing-kotlin-support-in-spring-framework-5-0 "target="_ blank ">since the beginning of 2017 Kotlin has also become justifiable in the development of entire backend systems.

And this is what Kotlin looks like

zero check

Before we dive into real world Kotlin code together, let's first consider a simple Java class as a reference. The callIfMatch() method takes a string parameter nullableString. This value could be null when passed to the method, hence the name nullable String. The very first thing the method does is tries to write the value of nullableString to the log output. It is checked whether its value is null, if yes, the value of nullableString is transferred, if not a default value of "defaultString". Then a if loop is used to check whether the value of the method parameter matches "matchMe". If so, a generic call() is called. It is checked again for null in the loop. This redundancy is intentional for comparison purposes and not necessarily unusual.

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

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

Next up is the Kotlin counterpart to the Java class above with identical functionality. We immediately notice that fewer characters are needed for equivalent business logic. The method callIfMatch() also accepts a string parameter nullableString and explicitly declares when determining its type String? that the value could be null with a question mark. Incidentally, the type declaration for Java connoisseurs comes after the parameter / variable name, so the question mark keyword is intuitive. This tells the compiler in advance that this value must be handled differently and can be null at runtime. When the value is called, the question mark keyword is also added to the variable name in order to explicitly declare this possibility. The compiler then knows how to handle it at runtime.

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

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

multiple branches

Another typical case in the real world are case distinctions using if/else or switch. Here we look at the first case for illustration. The following showStatusText() method returns a string value. This is filled with technically different values using a if/else. The instance type of the someState object is decisive for the case distinction. This can either be Connected, Connecting, Disconnected. The instance type is checked in Java with instanceof. Depending on the value of text, there is a different return value of "Status: {Connected | Connecting | Disconnected}. Please take note!".

Java
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!"
}

Just like in the previous example, you notice that fewer characters are needed for the equivalent logic and the whole code is thus leaner. In Kotlin, other Keywords are used for this case and a slightly different variable assignment is used. The variable text is assigned a value that corresponds to the return value of when. This when expression checks the status of someState and thus decides on the case distinction which value can be assigned to text. It is also interesting how the whole string is put together at the end. Instead of concatenating several strings via +, the value of the variable in the string can be displayed directly via $.

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

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

We hope that with these two concrete examples we could illustrate the leanness and intuitive use of best practices of modern programming languages like Kotlin. Such features make writing, reading and especially the maintenance of a codebase much easier.

Try it out for yourself

If we have managed to bring you closer to Kotlin and you feel the need to lend a hand yourself, it should be said that there are a variety of online environments in which Kotlin can be written and tried out right away. One of these online environments is the Kotlin Playground. The code is compiled and executed via the web application:

Kotlin Playground

If you have any further questions about Kotlin, we at b-nova value innovation through new technologies and are not afraid to use new programming languages such as Kotlin and use them in your project.

Further Links:

Ktor Framework | Build Asynchronous Servers and Clients in Kotlin

Spring Boot | Building web applications with Spring Boot and Kotlin


This text was automatically translated with our golang markdown translator.

Raffael Schneider – crafter, disruptor, free spirit. As a fervent software craftsmanship, Raffael likes to write about programming languages and software resilience in modern distributed systems. Be it DevOps, SRE or systems architecture, he always got a new way of approaching things.