Skip to content
AgileLogics
6 min read

The when Expression

Prerequisites: Conditionals

when checks a value against several options and runs the first one that matches. It replaces long if/else if chains and the switch statement of other languages — and it's far more flexible.

Syntax

when (value) {
    option1 -> result1
    option2, option3 -> result2
    else -> otherwise
}

Example

fun main() {
    val day = "Saturday"

    when (day) {
        "Saturday", "Sunday" -> println("Weekend!")
        "Friday" -> println("Almost weekend")
        else -> println("Weekday")
    }
}

Expected output

Weekend!

Only the matching branch runs — there's no "fall-through" into the next one, and no break needed.

Ranges, types, and conditions

when can match ranges and types, and produce a value:

fun describe(x: Any): String = when (x) {
    0 -> "zero"
    in 1..9 -> "a small number"
    is Int -> "a big number"
    is String -> "some text of length ${x.length}"
    else -> "something else"
}

fun main() {
    val score = 84
    val grade = when {
        score >= 90 -> "A"
        score >= 80 -> "B"
        score >= 70 -> "C"
        else -> "F"
    }
    println(grade)

    println(describe(0))
    println(describe(5))
    println(describe(500))
    println(describe("hi"))
    println(describe(2.5))
}
B
zero
a small number
a big number
some text of length 2
something else
  • in 1..9 matches a range.
  • is String matches a type — and smart-casts x to a String in that branch, so x.length works.
  • when with no argument (when { ... }) checks independent conditions — a tidy replacement for if/else if chains.
  • As an expression, when needs an else unless the compiler can see every possibility is covered (as with enums and sealed types in Level 2).

Any is the type every other Kotlin type belongs to.

Practice

Given a month from 1 to 12, print the season (Northern Hemisphere): 12, 1, 2 → winter; 3–5 → spring; 6–8 → summer; 9–11 → autumn.

Show solution
fun main() {
    val month = 7

    val season = when (month) {
        12, 1, 2 -> "winter"
        in 3..5 -> "spring"
        in 6..8 -> "summer"
        in 9..11 -> "autumn"
        else -> "invalid month"
    }
    println(season)
}
summer