← Back to Kotlin Course | Chapter 3: Control Flow | Lesson 2 of 7

when Expression

when is Kotlin's way of checking a value against a list of possibilities and running the matching option, like a smarter switch statement.

Basic when Usage

when compares a subject value against a series of branches and executes the first one that matches, replacing long if/else if chains with clearer syntax.

Example: Basic when Usage

markup
fun main() {
    val day = 3
    when (day) {
        1 -> println("Monday")
        2 -> println("Tuesday")
        3 -> println("Wednesday")
        else -> println("Some other day")
    }
}

Matching Multiple Values

A single branch can match several values at once by separating them with commas, avoiding repeated branches for cases that should behave the same way.

Example: Matching Multiple Values

markup
fun main() {
    val letter = 'a'
    when (letter) {
        'a', 'e', 'i', 'o', 'u' -> println("Vowel")
        else -> println("Consonant")
    }
}

Matching Ranges

Using in inside a when branch checks whether the value falls within a range, which is much clearer than several chained comparisons.

Example: Matching Ranges

markup
fun main() {
    val score = 85
    when (score) {
        in 90..100 -> println("Grade A")
        in 80..89 -> println("Grade B")
        in 70..79 -> println("Grade C")
        else -> println("Grade F")
    }
}

when as an Expression

when can produce a value directly, with each branch's result becoming the overall value when that branch matches. An else branch is required unless the compiler can prove every case is covered.

Note: when { } with no subject lets each branch be its own boolean condition.

Example: when as an Expression

markup
fun main() {
    val number = 4
    val description = when {
        number % 2 == 0 -> "even"
        else -> "odd"
    }
    println("$number is $description")
}
Common Mistakes
  1. Forgetting the else branch when using when as an expression on a type that is not exhaustive, causing a compile error.
  2. Not realizing when can match ranges, multiple values, and even types, and instead writing a long chain of if/else if.
  3. Writing overlapping conditions in a when without an argument, not realizing only the first matching branch runs.
Chapter Summary
  • when compares a value against several branches and runs (or evaluates to) the first one that matches.
  • A single branch can match multiple values separated by commas, or a range using in.
  • When used as an expression, when generally needs an else branch unless the compiler can prove all cases are covered (e.g. a sealed class or Boolean).
  • when can also be used with no argument at all, acting like a cleaner chain of conditions.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.