Kotlin when Expression (Switch Alternative) with Examples

Kotlin course · Control flow · Lesson 14 of 51

when is Kotlin’s replacement for the switch statement in Java and C, and it’s much more powerful. Use it when you compare one value against many possible cases.

Basic when

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")
    }
}

Output:

Wednesday

Kotlin checks the branches from top to bottom and runs the first one that matches. There’s no break, and no “fall-through” to the next branch.

Several values in one branch

Separate values with commas:

fun main() {
    val day = "Sat"
    when (day) {
        "Sat", "Sun" -> println("Weekend")
        "Mon", "Tue", "Wed", "Thu", "Fri" -> println("Weekday")
        else -> println("Unknown day")
    }
}

Output:

Weekend

Ranges with in

fun main() {
    val marks = 83
    when (marks) {
        in 90..100 -> println("Grade A")
        in 75..89 -> println("Grade B")
        in 50..74 -> println("Grade C")
        in 0..49 -> println("Fail")
        else -> println("Invalid marks")
    }
}

Output:

Grade B

when as an expression

Like if, when returns a value. You can assign it straight to a variable:

fun main() {
    val code = 404
    val message = when (code) {
        200 -> "OK"
        301, 302 -> "Redirect"
        404 -> "Not found"
        in 500..599 -> "Server error"
        else -> "Unknown status"
    }
    println(message)
}

Output:

Not found

When when is used as an expression, it must be exhaustive: every possible value must be covered, which usually means you need an else branch.

when without an argument

Leave out the value and write a full condition in each branch. This is a cleaner replacement for long if-else if chains:

fun main() {
    val temperature = 8
    val isRaining = true

    when {
        temperature < 0 -> println("Freezing")
        temperature < 10 && isRaining -> println("Cold and wet: take an umbrella")
        temperature < 10 -> println("Cold")
        else -> println("Pleasant")
    }
}

Output:

Cold and wet: take an umbrella

Checking types with is

fun describe(x: Any): String = when (x) {
    is Int -> "Int, doubled = ${x * 2}"
    is String -> "String of length ${x.length}"
    is Boolean -> "Boolean: $x"
    else -> "Something else"
}

fun main() {
    println(describe(21))
    println(describe("Kotlin"))
    println(describe(true))
    println(describe(3.5))
}

Output:

Int, doubled = 42
String of length 6
Boolean: true
Something else

Inside the is Int branch, Kotlin already knows x is an Int, so you can call x * 2 without converting. This is called a smart cast.

Blocks in a branch

Use braces when a branch needs more than one statement. The last expression is the branch’s value:

fun main() {
    val choice = 2
    val price = when (choice) {
        1 -> 99
        2 -> {
            println("You picked the yearly plan")
            899
        }
        else -> 0
    }
    println("Price: ₹$price")
}

Output:

You picked the yearly plan
Price: ₹899

when vs if-else

Use when when…Use if when…
you compare one value against many casesyou have one or two conditions
you check ranges or typesthe conditions are unrelated
you’d otherwise write 3+ else if branchesa simple yes/no is enough

Common mistakes

  • Missing else in an expression: val x = when (n) { 1 -> "one" } doesn’t compile.
  • Overlapping ranges: if in 50..100 comes before in 90..100, a 95 matches the first one.
  • Adding break: Kotlin’s when never falls through, so there’s nothing to break out of.

Exercise

Write a simple calculator: given two numbers and an operator symbol, print the result. Then compare it with our calculator using when, the practice lesson that follows this one.

fun main() {
    val a = 12.0
    val b = 4.0
    val op = '/'

    val result = when (op) {
        '+' -> a + b
        '-' -> a - b
        '*' -> a * b
        '/' -> if (b != 0.0) a / b else Double.NaN
        else -> Double.NaN
    }
    println("$a $op $b = $result")
}

Output:

12.0 / 4.0 = 3.0

FAQ

Is when the same as switch in Kotlin?

when replaces switch, but it can also match ranges, types and any condition, and it returns a value.

Does Kotlin when need break?

No. Only the first matching branch runs, and there’s no fall-through.

Is else required in when?

Only when when is used as an expression and the branches don’t already cover every possible value.

WhatsApp us📞 Call now