Kotlin when Expression

Kotlin when Construct

The when construct in Kotlin can be thought of as a replacement for Java switch Statement. It evaluates a section of code among many alternatives.


Example: Simple when Expression

fun main(args: Array<String>) {

    val a = 12
    val b = 5

    println("Enter operator either +, -, * or /")
    val operator = readLine()

    val result = when (operator) {
        "+" -> a + b
        "-" -> a - b
        "*" -> a * b
        "/" -> a / b
        else -> "$operator operator is invalid operator."
    }

    println("result = $result")
}

When you run the program, the output will be something like:

Enter operator either +, -, * or /
*
result = 60

The program above takes an input string from the user (Recommended Reading: Get String Input from the User in Kotlin). Suppose, the user entered *. In this case, the expression a * b is evaluated, and the value is assigned to variable result.

If none of the branch conditions are satisfied (user entered anything except +, -, *, or /) , else branch is evaluated.


In the above example, we used when as an expression. However, it's not mandatory to use when as an expression. For example,

fun main(args: Array<String>) {

    val a = 12
    val b = 5

    println("Enter operator either +, -, * or /")
    val operator = readLine()

    when (operator) {
        "+" -> println("$a + $b = ${a + b}")
        "-" -> println("$a - $b = ${a - b}")
        "*" -> println("$a * $b = ${a * b}")
        "/" -> println("$a / $b = ${a / b}")
        else -> println("$operator is invalid")
    }
}

When you run the program, the output will be something like:

Enter operator either +, -, * or /
-
12 - 5 = 7

Here, when is not an expression (return value from when is not assigned to anything). In this case, the else branch is not mandatory.


Few possibilities

Combine two or more branch conditions with a comma. For example,

fun main(args: Array<String>) {

    val n = -1

    when (n) {
        1, 2, 3 -> println("n is a positive integer less than 4.")
        0 -> println("n is zero")
        -1, -2 -> println("n is a negative integer greater than 3.")
    }
}

When you run the program, the output will be:

n is a negative integer greater than 3.

Check value in the range. For example,

fun main(args: Array<String>) {

    val a = 100

    when (a) {
        in 1..10 -> println("A positive number less than 11.")
        in 10..100 -> println("A positive number between 10 and 100 (inclusive)")
    }
}

When you run the program, the output will be:

A positive number between 10 and 100 (inclusive)

Check if a value is of a particular type.

To check whether a value is of a particular type in runtime, we can use is and !is operator. For example,

when (x) {
    is Int -> print(x + 1)
    is String -> print(x.length + 1)
    is IntArray -> print(x.sum())
}

Use expressions as branch condition. For example,

fun main(args: Array<String>) {

    val a = 11
    val n = "11"

    when (n) {
        "cat" -> println("Cat? Really?")
        12.toString() -> println("Close but not close enough.")
        a.toString() -> println("Bingo! It's eleven.")
    }
}

When you run the program, the output will be:

Bingo! It's eleven.
Did you find this article helpful?