O'Reilly logo

Android Development with Kotlin by Igor Wojda, Marcin Moskala

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

The when expression

The when expression in Kotlin is a multiway branch statement. The when expression is designed as a more powerful replacement of the Java switch... case statement. The when statement often provides a better alternative than a large series of if... else if statements, but it provides more concise syntax. Let's look at an example:

    when (x) { 
        1 -> print("x == 1") 
        2 -> print("x == 2") 
        else -> println("x is neither 1 nor 2") 
    } 

The when expression matches its argument against all branches one after another until the condition of some branch is satisfied. This behavior is similar to Java switch... case, but we do not have to write a redundant break statement after every branch.

Similar to the if clause, we can use when either ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required