TExcelTAD
Home › Kotlin › Kotlin When

Kotlin When

when is Kotlin's answer to switch — but much more flexible. It matches a value against several branches, can check ranges and types, and, like if, it is an expression that can return a value.

Basic when

kotlin · try it yourself
fun main() {
    val day = 3
    when (day) {
        1 -> println("Monday")
        2 -> println("Tuesday")
        3 -> println("Wednesday")
        4 -> println("Thursday")
        5 -> println("Friday")
        else -> println("Weekend")
    }
}
Wednesday

Each branch is condition -> result. Only the first matching branch runs — there is no "fall-through" and no break needed.

when as an expression

kotlin · try it yourself
fun main() {
    val code = 404
    val message = when (code) {
        200 -> "OK"
        301, 302 -> "Redirect"
        404 -> "Not Found"
        500 -> "Server Error"
        else -> "Unknown"
    }
    println("$code: $message")
}
404: Not Found

Several values can share a branch when separated by commas (301, 302). When when is used as an expression, the compiler requires it to be exhaustive — usually that means an else branch.

Ranges, collections and types

Branch conditions can be much more than constants:

Condition Matches when
5 the subject equals 5
1, 2, 3 equals any of them
in 1..9 is inside the range
!in list is not in the collection
is String has that type (and is smart-cast)
kotlin · try it yourself
fun grade(score: Int): String = when (score) {
    in 90..100 -> "A"
    in 80..<90 -> "B"
    in 70..<80 -> "C"
    in 0..<70 -> "F"
    else -> "invalid"
}

fun main() {
    for (s in listOf(95, 83, 71, 40, 120)) {
        println("$s -> ${grade(s)}")
    }
}
95 -> A
83 -> B
71 -> C
40 -> F
120 -> invalid

Type checks with is automatically smart-cast the subject inside the branch, so you can call that type's members directly:

kotlin · try it yourself
fun describe(x: Any): String = when (x) {
    is Int -> "an Int, doubled is ${x * 2}"
    is String -> "a String of length ${x.length}"
    is Boolean -> if (x) "yes" else "no"
    else -> "something else"
}

fun main() {
    println(describe(21))
    println(describe("hello"))
    println(describe(true))
    println(describe(3.5))
}
an Int, doubled is 42
a String of length 5
yes
something else

when without a subject

Leave out the parentheses and each branch becomes a full Boolean condition. This is a clean replacement for long if … else if chains:

kotlin · try it yourself
fun main() {
    val temp = 12
    val windy = true

    val advice = when {
        temp > 25 -> "T-shirt weather"
        temp > 15 && !windy -> "Light sweater"
        windy -> "Windbreaker"
        else -> "Warm coat"
    }
    println(advice)
}
Windbreaker

Missing else

If you forget else in a when expression that isn't exhaustive, the compiler tells you:

kotlin · try it yourself
fun main() {
    val n = 2
    val word = when (n) {
        1 -> "one"
        2 -> "two"
    }
    println(word)
}
File.kt:3:16: error: 'when' expression must be exhaustive. Add an 'else' branch.

Tip: With enums and sealed classes, when can be exhaustive without else — the compiler knows every possible case. That's covered in the OOP section.

Test yourself

Do you need break at the end of a when branch?

  1. Yes, always
  2. No, only the matching branch runs; there is no fall-through
  3. Only for the else branch
  4. Only in loops

How do you match several values in one branch?

  1. 1 | 2 -> ...
  2. 1, 2 -> ...
  3. 1 or 2 -> ...
  4. case 1, case 2 -> ...

What does when { ... } without a subject do?

  1. It is a syntax error
  2. Each branch is evaluated as a Boolean condition
  3. It matches against null
  4. It runs every branch