Kotlin when Expression

The when expression is Kotlin's replacement for switch statements in other languages. It is more powerful, more readable, and works as both a statement and an expression that returns a value.

Basic when Statement

val day = 3

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

Output: Wednesday

How when Works


                 day = 3
                    │
           when (day) checks each branch:
                    │
        ┌─────── day == 1? No ──────┐
        │                           │
        └─────── day == 2? No ──────┤
                                    │
        ┌─────── day == 3? YES ─────┘
        │
        ▼
   println("Wednesday")  ← executes this, stops checking

when as an Expression

val code = 404

val message = when (code) {
    200 -> "OK"
    201 -> "Created"
    400 -> "Bad Request"
    401 -> "Unauthorized"
    404 -> "Not Found"
    500 -> "Server Error"
    else -> "Unknown code"
}

println(message)  // Not Found

Multiple Values in One Branch

val month = 6

val season = when (month) {
    12, 1, 2  -> "Winter"
    3, 4, 5   -> "Spring"
    6, 7, 8   -> "Summer"
    9, 10, 11 -> "Autumn"
    else      -> "Unknown"
}

println(season)  // Summer

when with Ranges

val score = 85

val grade = when (score) {
    in 90..100 -> "A"
    in 75..89  -> "B"
    in 60..74  -> "C"
    in 50..59  -> "D"
    else       -> "F"
}

println("Grade: $grade")  // Grade: B

when Without an Argument

You can use when without a value in the parentheses. Each branch then acts like an if-else condition:

val temp = 38.5
val humidity = 80

when {
    temp > 40              -> println("Extreme heat warning")
    temp > 35 && humidity > 70 -> println("Hot and humid, stay indoors")
    temp > 30              -> println("Warm day, stay hydrated")
    else                   -> println("Pleasant weather")
}

when with Type Checks

fun describe(item: Any) {
    when (item) {
        is Int    -> println("Integer: $item")
        is String -> println("String of length ${item.length}")
        is Boolean -> println("Boolean: $item")
        is List<*> -> println("List with ${item.size} items")
        else      -> println("Unknown type")
    }
}

fun main() {
    describe(42)
    describe("Kotlin")
    describe(true)
    describe(listOf(1, 2, 3))
}

Output:

Integer: 42
String of length 6
Boolean: true
List with 3 items

Multi-Line Branch Blocks

val command = "start"

when (command) {
    "start" -> {
        println("Initializing...")
        println("System started.")
    }
    "stop" -> {
        println("Saving data...")
        println("System stopped.")
    }
    else -> println("Unknown command: $command")
}

Practical Example: Day Type Checker

fun main() {
    val day = "Saturday"

    val type = when (day) {
        "Monday", "Tuesday", "Wednesday",
        "Thursday", "Friday" -> "Weekday"
        "Saturday", "Sunday" -> "Weekend"
        else -> "Invalid day"
    }

    println("$day is a $type")
}

Output:

Saturday is a Weekend

Leave a Comment

Your email address will not be published. Required fields are marked *