From Java to Kotlin, with Love – Part 3

In parts 1 and 2 we explored, from a Java point of view, features of Kotlin that makes it both a concise and safe language. In this article, we will compare and another aspect to Kotlin with Java which is conditionals.

I always cringe when I see an if statement that looks like this:

if (someCondition)
   someVariable = value1;
else
   someVariable = value2;

In this situation I am a big fan of the shorthand ?: ternary operator. I would always rewrite the above snippet more concisely to look like this:

someVariable = (someCondition) ? value1 : value2;

It is indeed more concise but it looks a bit foreign and less expressive than the if statement.

In Kotlin, the if statement is an expression in itself, so you can combine the expressiveness with the brevity as follows:

someVariable = if (someCondition) value1 else value2

So you can write a function that looks like this:

fun someFunction() {
    return if (someCondition) value1 else value2
}

This is pretty neat especially when combined with the shorthand for single-expression function declaration:

fun someFunction = if (someCondition) value1 else value2

What is even nicer is the when expression, which is much more powerful than the classic switch statement. Let us take an example:

var obj: Any
when (obj) {
    10          ->  println("Dime")
    "Merci"     ->  println("That is French!")
    is Long     ->  println("Long")
    in 1..(y-1) ->  println("Less than y.")
    else        ->  println("Alien creature.")
}

There quite a few advancements over a switch statement:

  1. The variable used can be anything, and not just something convertible to an integer as in Java.
  2. The value in each matching case can also be of any type, or even an expression and not just a constant that has to be determined at compile-time.
  3. The else clause is mandatory, unless the compiler can prove that the cases cover every possibility. In a typical switch the default clause is optional, which can cause some cases to go unhandled unintentionally.
  4. And of course, there is no case keyword, and more importantly there is annoying break required after each case.

Like the if statement, when can be used as an expression, so the previous block may be written like this:

var obj: Any
var message: String = when (obj) {
    10          -> "Dime"
    "Merci"     -> "That is French!"
    is Long     -> "Long"
    in 1..(y-1) -> "Less than y."
    else        -> "Alien creature."
}
println(message)

Pretty powerful!

Leave a comment