Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 134 ยท Control Flow

when Expressions

Learn Kotlin's when expression - matching values, ranges, types and conditions, subject-less when, exhaustiveness with enums and sealed types, guard conditions, and when versus if-else chains.

Every language eventually needs a way to choose between many alternatives. Java has switch, C has switch, Python has match. Kotlin has when, and it is far more capable than a classic switch: it matches values, ranges, collections, types and arbitrary conditions, it can be used as an expression that returns a value, and with enums and sealed types the compiler checks that you covered every case.

If you have just read if as an Expression, think of when as the clean way to write a long else if chain. You will use it constantly, from small decisions to modeling whole program states with sealed classes.

The basic form

when (subject) { ... } compares the subject with each branch condition from top to bottom. The first match runs, and there is no fall-through: you never write break.

Kotlin when with a subject

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

When when is used as an expression, its value is the value of the matching branch, exactly like if. A comma separates several alternatives for one branch. And because there is no fall-through, a whole category of switch bugs, where a forgotten break runs the next case too, simply cannot happen.

else

When when is used as an expression, it must be exhaustive, so an else branch is required unless the compiler can prove all cases are covered (enums, sealed types, Boolean). As a statement, else is optional for ordinary values.

Kotlin when expression without else (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The compiler reports 'when' expression must be exhaustive. Add the 'else' branch. Adding else -> "Unknown" fixes it. Resist the urge to write else -> "?" everywhere; for closed sets of values (enums and sealed classes) leaving else out is better, as shown later, because a new case then breaks the build instead of silently falling into else.

What a branch condition can be

The part before -> is much more flexible than a constant:

Kotlin Ranges, collections, types and expressions as conditions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The branch types you can use:

  • a constant or any expression: 5 ->, "yes" ->, limit -> (the value is compared with ==);
  • several values separated by commas: 1, 2, 3 ->;
  • in range, in collection, !in ... to test membership;
  • is Type and !is Type to test the runtime type, with a smart cast inside the branch;
  • with no subject, any Boolean expression.

Notice that in 1..9 works even though the subject has type Any: for a value that is not an Int the range check is simply false, so the program reaches the is String branch for the text. The same leniency makes !in dangerous on an Any subject: !in 0..1000 is true for every non-number, so such a branch would swallow strings and lists before their is branches get a turn. Put the is checks first, or give the function a precise parameter type.

when without a subject

If you drop the parentheses after when, each branch condition is just a Boolean expression, and the first true one wins. This is the clean replacement for long if / else if chains:

Kotlin when as a cleaner else-if chain

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Order matters: because evaluation stops at the first true, put narrower conditions before broader ones. In describeBmi each branch implicitly means "and all the previous ones were false", which is why you only need an upper bound.

Capturing the subject

You can declare a variable in the parentheses, scoped to the when. It is useful when the subject is a call you want to evaluate once:

Kotlin when with a declared subject

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Exhaustiveness with enums, Booleans and sealed types

For some types the compiler knows every possible value. A when expression over such a type needs no else, and if you forget a case, it will not compile:

Kotlin Exhaustive when over an enum

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Now add a fourth entry BLINKING to the enum without touching action, and the build stops with 'when' expression must be exhaustive. Add the 'BLINKING' branch or an 'else' branch. That compile error is a feature: it lists every place that must handle the new case. The same safety applies to sealed classes and interfaces (Sealed Classes and Interfaces). If you had written else, the new case would be swallowed silently.

For enums and sealed types, avoid else. Let the compiler tell you where new cases need handling. Use else only for open-ended values such as numbers and strings.

Guards: extra conditions in a branch

When the subject is matched by type or value, you sometimes need one more test. The guard syntax if after the condition does that:

Kotlin Guard conditions with if in a branch

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Guards (is Circle if shape.radius == 0.0) became a stable language feature in Kotlin 2.2 and compile without any flags on the version we run here; on an older toolchain you would need to write the extra test as a separate branch or with a subject-less when. A branch is taken only when both the pattern and the guard hold. You can combine conditions with && or || inside the guard. Each guarded branch must be followed later by an unguarded one for the same type, as above, or the when is not exhaustive.

when, returning, and early exits

when branches can return, throw or continue too, since those have type Nothing. This turns when into a tidy validator:

Kotlin when with throw branches (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The last call prints nothing for that line and ends the program with java.lang.IllegalArgumentException: unknown operator '^'. That is the right outcome: an unknown operator is a bug in the caller, so fail loudly. Here each branch is a lambda (see Lambdas), which shows that a when can return functions, not just numbers and strings.

when versus if-else

  • Two alternatives: if/else.
  • Three or more alternatives on the same subject: when.
  • Checking the type of a value: when with is.
  • Closed sets (enum, sealed): when without else.
  • Unrelated conditions: subject-less when.

Performance is not a concern: for constants and enums the compiler generates efficient jump tables, and in all cases it is as fast as the equivalent if chain.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What happens after a when branch finishes running?

    Only the first matching branch runs. Kotlin has no fall-through, so no break is needed.
  2. 2. Which when form replaces a long if / else if chain of unrelated conditions?

    A subject-less when evaluates each Boolean condition in order and takes the first one that is true.
  3. 3. Why is it a good idea to leave out else when matching all entries of an enum?

    Without else, the when expression must be exhaustive, so adding an entry breaks the build until every when handles it.
  4. 4. What does a when expression require when it is used as a value and the subject is an Int?

    Used as an expression, when must cover all cases. For an Int subject only else can guarantee that.
  5. 5. In is Circle if shape.radius == 0.0 -> ..., what is if shape.radius == 0.0?

    A guard adds a second condition to a branch. Both the pattern and the guard must hold.

Summary

  • when picks the first matching branch; there is no fall-through and no break.
  • Branch conditions can be values, comma lists, in ranges or collections, is type tests, or (without a subject) any Boolean expression.
  • As an expression when must be exhaustive: use else, or cover every enum entry, Boolean value or sealed subtype.
  • Leave else out for enums and sealed types so the compiler flags forgotten cases.
  • when (val x = ...) scopes a variable to the when; guards (is T if cond) add extra tests to a branch.
  • Branches may return, throw or yield functions, and when is the idiomatic replacement for chains of if.

Next: Loops