Kotlin When

Kotlin When Expression

Instead of writing many if..else if expressions, you can use the when expression. It is much easier to read and allows you to test a variable against multiple values.

The when expression is similar to the switch statement in Java or C.


The when Syntax

Example

fun main() {
  val day = 4

val result = when (day) { 1 -> "Monday" 2 -> "Tuesday" 3 -> "Wednesday" 4 -> "Thursday" 5 -> "Friday" 6 -> "Saturday" 7 -> "Sunday" else -> "Invalid day." } println(result) }

In this example:

  1. The when block evaluates the day variable.
  2. It matches the value of day (which is 4) with the case 4 -> "Thursday".
  3. It assigns "Thursday" to the result variable.

The else Branch

The else branch is executed if none of the other cases match. If you are using when as an expression (assigning it to a variable), the else branch is mandatory unless the compiler can prove all possible cases are covered.