Kotlin: How to use the ‘when’ expression

In addition to if, for, and while loops, Kotlin also has a control flow option called when. The ‘when’ expression acts just like a switch operator you might see in other languages. The basic structure looks like this:

when (variableToBeExamined) {
    1 -> print("variableToBeExamined is set to 1")
    2 -> print("variableToBeExamined is set to 2")
    else -> { // Note the curly braces
        print("variableToBeExamined contains neither 1 nor 2")

Some notes about this switch structure:

  • The first line uses the key word when followed by a variable name in parenthesis
  • The entire ‘when’ structure is wrapped in curly braces
  • The values that we want to set switch cases on go on the left, followed by an arrow operator -> and then what we want to have happen for each condition goes on the right side
  • We can use an else block at the end of the when structure, but it requires its own set of curly braces! (when the when structure is used as an expression)

Here is what kotlinlang.org docs say about when:

when matches its argument against all branches sequentially until some branch condition is satisfied. when can be used either as an expression or as a statement. If it is used as an expression, the value of the satisfied branch becomes the value of the overall expression. If it is used as a statement, the values of individual branches are ignored. (Just like with if, each branch can be a block, and its value is the value of the last expression in the block.)

The else branch is evaluated if none of the other branch conditions are satisfied. If when is used as an expression, the else branch is mandatory, unless the compiler can prove that all possible cases are covered with branch conditions (as, for example, with enum class entries and sealed class subtypes).

It is also possible to combine values on the left, separated by a comma. For example:

when (x) {
    0, 1, 2, 3, 4 -> print("x is between 0 and 4")
    else -> print("x is not a value between 0 and 4")

Another way to do the same thing as above, but using ranges (with the in .. notation):

when (x) {
    in 0..4 -> print("x is in the range")
    in validNumbers -> print("x is valid")
    in 5..20 -> print("x is outside the range")
    else -> print("none of the above")

In addition to using when as a switch statement or expression, it can also be used as a replacement for an if-else if chain. In this case, there are no parenthesis after the ‘when’. For example:

when {
    x.isOdd() -> print("x is odd")
    x.isEven() -> print("x is even")
    else -> print("x is not a number")

One more example of what can be done with when. Inside the ‘when’ parenthesis, it is possible to set a variable that is based on a function call, and then use that variable in the body of the ‘when’ structure. For example:

fun Request.getBody() =
        when (val response = executeRequest()) {
            is Success -> response.body
            is HttpError -> throw HttpException(response.status)

For more information about Kotlin control flow options, including the when structure, see: