Start learning free

LESSON 92 OF 677 · CONDITIONAL STATEMENTS

when: the switch that returns a value

Lesson

Other languages have switch. Kotlin has when — and it does more, because when is an expression: the whole block evaluates to the value of whichever branch matches, so you can assign the result directly to a variable. No temporary variable, no assignment repeated in every branch.

val score = 95
val grade = when (score) {
    in 90..100 -> "A"    // range check: 90 to 100, both ends included
    in 80..89 -> "B"
    else -> "F"
}
// grade is "A"

Each branch has the shape match -> result, and the match can be:

  • a plain value: 1 -> "one"
  • several values in one branch, comma-separated: 6, 7 -> "weekend"
  • a range: in 90..100 -> "A"
  • else — everything the branches above didn't catch

Branches are checked top to bottom and the first match wins, exactly like an if/else-if ladder — just far easier to read.


The trap:

The moment you USE the value of a when — assign it, return it — the compiler must be able to produce a value for every possible input. This is called being exhaustive. Forget the else:

val grade = when (score) {
    in 90..100 -> "A"
    in 80..89 -> "B"
}   // ...what should grade be when score is 42?

...and compilation stops with:

error: 'when' expression must be exhaustive. Add an 'else' branch.
    val grade = when (score) {
                ^^^^

Read it once, remember it forever: expression when ⇒ cover every case, usually by ending with else. (A when whose result you ignore is just a statement and doesn't need one.) This strictness is a gift — the compiler catches the "forgot a case" bug before your users do.


Assignment
Follow the Coding Tutorial and build two when expressions:

  • create val score = 87 and convert it to a letter grade: in 90..100 -> "A", in 80..89 -> "B", else -> "F"; print it,
  • create val day = 3 and classify it with comma-separated match values: days 1, 2, 3, 4, 5 are "weekday", days 6, 7 are "weekend", anything else is "invalid"; print the day and its type.

The exact expected output is:

grade = B
day = 3, type = weekday

Hint
Both when blocks end with an else branch — leave one out and you'll meet the exhaustiveness error from above.


STEP 1 OF 10
    Ctrl + Enter to check