when Expressions (Kotlin's Switch)

when Expressions (Kotlin's Switch) in Kotlin: The fare machine bolted to the depot gate has a coin cascade inside it: a single steel rail set at a slight…

The Analogy: The Coin Cascade in the Fare Machine

The fare machine bolted to the depot gate has a coin cascade inside it: a single steel rail set at a slight downward angle, with a row of gaps cut into its floor. The gaps are not the same size. The first is cut for the smallest coin in circulation, the second a whisker wider, the third wider again, on down the rail to the last gap, cut for the largest coin the machine accepts. Beneath each gap sits a labelled bin, and beneath the far end of the rail, past the last gap, sits an unlabelled tray the fitters call the overflow.

Drop a coin in the top and the mechanism does something very specific. The coin rolls along the rail and is offered to gap one; if it is too wide to fall through, it rolls on to gap two, then gap three, and it falls through the first gap it fits. That is the whole of the logic. The rail does not measure the coin, does not compare it against all the gaps and pick the best match, and does not carry on testing after the coin has dropped. Once the coin is in a bin the remaining gaps might as well not exist, so the order in which the gaps were cut is the only thing deciding where any coin ends up.

That ordering is what makes the cascade trustworthy, and it is a rule you must respect when you build one: the gaps have to run narrow to wide. Cut them the other way about and every coin drops through the first gap, because the first gap is wide enough for all of them, and the bins downstream stay empty for ever while the machine reports that every fare was paid in the largest coin. The overflow tray carries the other half of the design. If the machine is built for exactly the six coins of one currency and each has a gap of its own, the tray should be empty at close of business, and anything found in it is a message: something went through here that the machine was not built to recognise.

The failure mode is quieter than a jam and much harder to find. A fitter is called out because a worn coin keeps sticking at gap two, and he eases the gap with a file -- a sensible ten-minute repair, recorded nowhere. The gap is now a fraction wider than the coin it was cut for, so the next size up, the one that used to drop at gap four, fits gap two and falls there instead. Nothing jams, no alarm sounds, fares keep being taken; the only symptom is that bin two is heavy and bin four is light, which nobody notices until the cash is counted and the tally sheet disagrees with the till. The overflow tray has a matching weakness: a foreign coin that fits no gap and a British coin worn so thin that it fits no gap end up in the same unlabelled tray, so the machine has thrown away the difference between "I have never seen this" and "I know exactly what this is and it is damaged." A Kotlin when is that cascade -- branches in the order you wrote them, first match taking the value, and else the unlabelled tray.


Syntax or Core Structure

A when has a subject in parentheses and a list of branches, each one a condition, an arrow, and the thing to do or the value to produce. It can be used as a statement, where the branch bodies do something, or as an expression, where each branch body is a value and the whole when evaluates to one of them. Drop the subject and every branch becomes an arbitrary boolean condition instead, which replaces the long if/else if chain that other languages need.

fun classify(kg: Int): String = when (kg) {
    in 0..3500 -> "CAR"
    in 3501..7500 -> "VAN"
    in 7501..18000 -> "HGV"
    else -> "SPECIAL"
}

fun main() {
    val lane = 3
    when (lane) {
        1 -> println("lane 1: exact change")
        2, 3 -> println("lane 2 or 3: cards and passes")
        else -> println("lane unknown")
    }

    val kg = 6800
    val band = classify(kg)
    println("band for 6800 kg: $band")

    val label: String = when (band) {
        "CAR" -> "light vehicle"
        "VAN", "HGV" -> "goods vehicle"
        else -> "referred to the supervisor"
    }
    println("label: $label")

    val ticket: Any = 4820
    val note = when (ticket) {
        is Int -> "numbered ticket " + ticket
        is String -> "written pass of " + ticket.length + " characters"
        else -> "unrecognised token"
    }
    println("note: $note")

    val hour = 7
    val tariff = when {
        hour < 6 -> "night"
        hour < 10 -> "morning peak"
        hour < 16 -> "day"
        else -> "evening"
    }
    println("tariff at 07: $tariff")
}

Output:

lane 2 or 3: cards and passes
band for 6800 kg: VAN
label: goods vehicle
note: numbered ticket 4820
tariff at 07: morning peak

Five branch forms appear there. The lane when is a statement: its branches call println and the when produces nothing, and 2, 3 -> shows that one branch can list several constants, which is how Kotlin replaces the deliberate fall-through of a C-style switch. classify uses in with a range, so a branch matches a span of values rather than one. label and note are expressions: the result is assigned, so every branch must produce a String and the compiler insists on else because it cannot prove the listed strings are all of them. note also shows is, which tests the type and smart-casts the subject inside that branch -- ticket.length compiles only because is String has already narrowed it. The tariff example has no subject at all, so its branches are plain conditions, and it returns "morning peak" because seven is not less than six but is less than ten.


Technical Depth: First Match Wins, Exhaustiveness and the Value It Returns

Three properties account for nearly everything about when: branches are tried in source order and the first match wins, branches never fall through, and the whole construct is an expression whenever you use it as one. The rest is a catalogue of the shapes a branch condition may take.

Branch formMatches whenTypical use
1 ->the subject is equal to that constantone known code
2, 3 ->the subject equals any constant in the listseveral codes, one outcome
in 1..9 ->the subject falls inside the rangenumeric bands
!in 1..9 ->the subject falls outside the rangerejecting a band up front
in setOf("A", "B") ->the collection contains the subjecta membership test
is String ->the runtime type matches, and the subject is smart-castmixed input of several types
!is String ->the runtime type does not matchearly rejection before the real work
null ->the subject is nulldealing with absence before the type branches
a bare condition, with no subjectthat condition evaluates to truetests of several unrelated things
else ->nothing above it matchedthe fallback, and the last resort

Whether you must write that fallback depends on the type of the subject and on whether the when is producing a value. The compiler can only check that you have covered every case when the set of cases is closed -- true of an enum, a sealed hierarchy and Boolean, not true of Int or String or Any.

SubjectUsed as a statementUsed as an expression
an enum classevery entry must be covered, or elsethe same, and one branch's value is returned
a sealed class or sealed interfaceevery direct subtype must be covered, or elsethe same
Booleanboth true and false must be covered, or elsethe same
Int, String, Anyno requirement; an unmatched subject does nothingelse is compulsory
no subject at allno requirementelse is compulsory

The statement rules for enums, sealed types and Boolean tightened in Kotlin 1.7: what used to be a warning is now an error, on the reasoning that a when over a closed set almost always wants to be complete whether or not anyone reads its result. That changes how you should think about else. On an Int subject it is plumbing you cannot avoid; on a sealed subject it is a decision, and usually the wrong one, because it is the thing that stops the compiler telling you about the new subtype somebody added last Tuesday.

Order decides the answer

Two functions below hold the same two range branches in opposite orders. Neither one is a compile error and neither one produces a warning, because overlapping ranges are perfectly legal; the compiler has no way to know which overlap you meant.

fun looseFirst(kg: Int): String = when (kg) {
    in 0..18000 -> "ANY"
    in 7501..18000 -> "HGV"
    else -> "SPECIAL"
}

fun tightFirst(kg: Int): String = when (kg) {
    in 7501..18000 -> "HGV"
    in 0..18000 -> "ANY"
    else -> "SPECIAL"
}

fun main() {
    println("loose first, 17400: ${looseFirst(17400)}")
    println("tight first, 17400: ${tightFirst(17400)}")
    println("loose first, 1240: ${looseFirst(1240)}")
    println("tight first, 1240: ${tightFirst(1240)}")
    println("same answer for 1240: ${looseFirst(1240) == tightFirst(1240)}")
    println("same answer for 17400: ${looseFirst(17400) == tightFirst(17400)}")
}

Output:

loose first, 17400: ANY
tight first, 17400: HGV
loose first, 1240: ANY
tight first, 1240: ANY
same answer for 1240: true
same answer for 17400: false

Look at the last two lines: the functions agree on 1240 and disagree on 17400, and neither is buggy -- each does exactly what its branches say. In looseFirst the wide range comes first, so the "HGV" branch below it can never be reached by any value at all; the coin has dropped through gap one before it ever reaches gap two. A when whose branches overlap has a meaning that lives in the order and nowhere else, and no type, signature or single-value test will tell you a later branch is dead. The defence is conditions that are mutually exclusive, so order stops mattering.

Exhaustiveness, and naming the subject in the header

When the subject's type has a closed set of values the compiler can check your work and will refuse a when that leaves a case out. That check is the strongest reason to model alternatives as an enum or a sealed hierarchy rather than as strings or integer codes.

enum class Lane { CASH, CARD, PASS }

sealed class Reading
class Weighed(val kg: Int) : Reading()
class SensorFault(val code: String) : Reading()
object NotPresent : Reading()

fun feeFor(lane: Lane): Int = when (lane) {
    Lane.CASH -> 250
    Lane.CARD -> 240
    Lane.PASS -> 0
}

fun describe(r: Reading): String = when (r) {
    is Weighed -> "weighed " + r.kg + " kg"
    is SensorFault -> "fault " + r.code
    NotPresent -> "nothing on the plate"
}

fun main() {
    for (lane in Lane.values()) {
        println("fee " + lane.name + ": " + feeFor(lane))
    }

    val readings = listOf(Weighed(6800), SensorFault("E12"), NotPresent)
    for (r in readings) println(describe(r))

    when (val n = readings.size) {
        0 -> println("no readings")
        in 1..2 -> println("a few readings: " + n)
        else -> println("many readings: " + n)
    }
}

Output:

fee CASH: 250
fee CARD: 240
fee PASS: 0
weighed 6800 kg
fault E12
nothing on the plate
many readings: 3

Neither feeFor nor describe has an else, and neither needs one: the three enum entries and the three direct subtypes of Reading are the whole set, so the compiler can see that every path returns. Add a fourth lane or a fourth kind of reading and both stop compiling, with an error pointing at exactly the place a decision is now missing -- that is what you buy by leaving else out. Note the two branch shapes in describe: is Weighed is a type test that smart-casts, so r.kg is reachable, while NotPresent is an equality test against an object declaration, which the exhaustiveness checker accepts as covering that subtype. The final when shows the header form, which evaluates the subject once and binds it to a name in scope in every branch.


Real World Example: Pricing a Day's Crossings at the Depot Gate

The gate charges by vehicle class, taken from the weighbridge rather than from anything the driver says. On top of that there is an axle surcharge, because more axles means more wear on the ramp, and a discount depending on the permit in the windscreen and sometimes on the class too. Four small decisions, none the same shape: numeric bands, a lookup by class name, a mix of single values and a range, and a test of two unrelated things at once. That is four when expressions, printed as a fixed-width table so every intermediate number can be checked against the totals.

const val CROSSINGS = "2:1240:NONE,2:-40:NONE,3:6800:TRADE,5:17400:TRADE,2:3500:RESIDENT,6:21000:NONE"

const val W_AXLES = 5
const val W_KG = 8
const val W_BAND = 9
const val W_BASE = 6
const val W_SUR = 5
const val W_DISC = 6
const val W_NET = 6

val BANDS = listOf("CAR", "VAN", "HGV", "SPECIAL")

fun bandFor(kg: Int): String = when (kg) {
    in 0..3500 -> "CAR"
    in 3501..7500 -> "VAN"
    in 7501..18000 -> "HGV"
    else -> "SPECIAL"
}

fun baseFor(band: String): Int = when (band) {
    "CAR" -> 250
    "VAN" -> 480
    "HGV" -> 1150
    else -> 1900
}

fun surchargeFor(axles: Int): Int = when (axles) {
    2 -> 0
    3, 4 -> 60
    in 5..8 -> 150
    else -> 300
}

fun discountFor(permit: String, band: String): Int = when {
    permit == "RESIDENT" -> 100
    permit == "TRADE" && band == "HGV" -> 200
    permit == "TRADE" -> 80
    else -> 0
}

fun row(axles: String, kg: String, band: String, base: String, sur: String, disc: String, net: String): String =
    axles.padStart(W_AXLES) + kg.padStart(W_KG) + band.padStart(W_BAND) +
        base.padStart(W_BASE) + sur.padStart(W_SUR) + disc.padStart(W_DISC) + net.padStart(W_NET)

fun main() {
    val width = W_AXLES + W_KG + W_BAND + W_BASE + W_SUR + W_DISC + W_NET
    val records = CROSSINGS.split(",")
    val tally = IntArray(BANDS.size)
    var totalBase = 0
    var totalSur = 0
    var totalDisc = 0
    var totalNet = 0

    println(row("AXLES", "KG", "BAND", "BASE", "SUR", "DISC", "NET"))
    println("-".repeat(width))

    for (record in records) {
        val parts = record.split(":")
        val axles = parts[0].toInt()
        val kg = parts[1].toInt()
        val permit = parts[2]

        val band = bandFor(kg)
        val base = baseFor(band)
        val sur = surchargeFor(axles)
        val disc = discountFor(permit, band)
        val net = base + sur - disc

        tally[BANDS.indexOf(band)]++
        totalBase += base
        totalSur += sur
        totalDisc += disc
        totalNet += net

        println(row(axles.toString(), kg.toString(), band,
            base.toString(), sur.toString(), disc.toString(), net.toString()))
    }

    println("-".repeat(width))
    println(row("ROWS", records.size.toString(), "TOTALS",
        totalBase.toString(), totalSur.toString(), totalDisc.toString(), totalNet.toString()))
    println("bands: " + BANDS.mapIndexed { i, b -> b + "=" + tally[i] }.joinToString(" "))
    println("sum of net column: " + totalNet)
    println("base " + totalBase + " + sur " + totalSur + " - disc " + totalDisc +
        " = " + (totalBase + totalSur - totalDisc) +
        " agree: " + (totalNet == totalBase + totalSur - totalDisc))
}

Output:

AXLES      KG     BAND  BASE  SUR  DISC   NET
---------------------------------------------
    2    1240      CAR   250    0     0   250
    2     -40  SPECIAL  1900    0     0  1900
    3    6800      VAN   480   60    80   460
    5   17400      HGV  1150  150   200  1100
    2    3500      CAR   250    0   100   150
    6   21000  SPECIAL  1900  150     0  2050
---------------------------------------------
 ROWS       6   TOTALS  5930  360   380  5910
bands: CAR=2 VAN=1 HGV=1 SPECIAL=2
sum of net column: 5910
base 5930 + sur 360 - disc 380 = 5910 agree: true

Follow the fourth crossing through all four decisions, because every one of them fires. Seventeen thousand four hundred kilograms falls in 7501..18000, so bandFor stops at the third gap and returns "HGV"; baseFor matches that string and charges 1150; five axles falls in 5..8, so surchargeFor adds 150; and the permit is "TRADE" while the band is "HGV", so the second branch of discountFor takes 200 off rather than the 80 the third branch would have given. Net is 1150 plus 150 minus 200, the 1100 in the last column. The third crossing takes a different path through the same function: also "TRADE", but band "VAN", so the second branch fails and the third gives 80.

None of the four could be written as one of the others. bandFor uses in with ranges because the input is a continuum and the output a small set of names. baseFor uses constant string branches because it is a four-entry lookup table, short enough that a table on the page beats a Map elsewhere. surchargeFor mixes a constant, a comma list and a range in one when. And discountFor has no subject at all, because its conditions test two different variables -- there is no single value to switch on, so inventing one would only obscure the rule.

The bottom three lines exist to be checked rather than read. The band tally comes from an IntArray indexed by position in BANDS, not a hash map, so CAR=2 VAN=1 HGV=1 SPECIAL=2 prints in declared order on every run and platform, and the counts sum to the six on the totals line. The last line recomputes the net total from the three column totals independently of the running sum and says whether they agree, turning a family of silent errors -- a branch that forgets to accumulate, a discount applied twice -- into a visible false.

The limits are real and one is a genuine design flaw rather than a rough edge. Look at the second crossing: minus forty kilograms, from a weighbridge never re-tared after the last vehicle drove off, and the gate has charged it 1900 pence, the most expensive line on the table. That happens because bandFor uses else to mean two things at once -- "heavier than the heaviest band we listed" and "not a weight a vehicle can have" -- and baseFor compounds it by pricing any string it does not recognise at the "SPECIAL" rate. The output reconciles perfectly, which is the worrying part: the totals line cannot tell that one of its inputs was nonsense, so the day's takings look correct while a driver has been overcharged sevenfold. The fix is not a bigger else but a smaller one -- have bandFor return a sealed type with an explicit Unclassifiable case and key baseFor on that type, and the compiler will refuse to let the caller print a price for a reading it cannot classify. Two smaller limits: each band boundary appears twice (3500 then 3501, 7500 then 7501), so shifting a threshold takes two edits; and row pads but never truncates, so a band name over nine characters silently shifts every column to its right.


Common Mistakes

  1. Expecting one branch to fall through into the next. There is no fall-through in Kotlin and no break to prevent it, so the C habit of stacking labels and letting control run on does not translate. If two subjects share an outcome, list them in one branch: 2, 3 ->.
  1. Putting the broad branch above the narrow one. in 0..18000 written before in 7501..18000 makes the second branch unreachable for every possible input, and nothing warns you. Overlapping conditions are legal, so the compiler assumes the order you wrote is the order you meant.
  1. Adding else to an enum or sealed when for safety. It is the opposite of safety. Without else the build fails the day somebody adds a case; with else that new case silently takes the fallback path, which is how a new payment type ends up billed at the default rate for a month before anybody notices.
  1. Writing free conditions in a when that has a subject. when (kg) { kg > 3500 -> ... } does not mean what it looks like: the branch condition is compared against the subject, so you are asking whether kg equals the boolean kg > 3500. Drop the subject and the conditions become conditions.
  1. Type-testing a generic type argument. is List<String> will not compile, because the element type is erased at runtime and the test could not be honest. Use is List<*> and then check the elements you actually intend to use.
  1. Assuming exhaustiveness on an open hierarchy. Only enums, sealed classes, sealed interfaces and Boolean give the compiler a closed set. A when over the subtypes of an ordinary open class can never be checked, so if that hierarchy matters, seal it.
  1. Ending a block branch with a statement. The value of a block branch is its last expression, so a trailing println or a trailing val declaration makes that branch Unit and the when stops type-checking. The error usually points at the assignment rather than at the branch.
  1. Allocating inside a branch condition. in listOf("A", "B", "C") builds a fresh list every time the when is evaluated. Over a million records that is a million allocations to answer a question a setOf constant declared once could answer for free.
  1. Letting else swallow null. If the subject is nullable, else matches null along with everything else, so a missing value quietly takes the fallback path. Write an explicit null -> branch first whenever null means something different from unrecognised.

Best Practices

  • Write branch conditions that cannot both hold, so order stops carrying meaning. When order genuinely must matter, put the narrowest condition first and say in a comment that the sequence is load-bearing.
  • Prefer the expression form. Assigning or returning the result forces every path to produce a value and makes a forgotten case a compile error rather than a variable that kept its old contents.
  • Model a closed set of alternatives as an enum or a sealed hierarchy, then leave else out on purpose. The missing else turns "somebody added a case" into a build failure at exactly the sites that need editing.
  • Use when (val x = subject()) when the subject is a call. It is evaluated once, named for every branch to use, and scoped to the when so it cannot leak into the code below.
  • Keep numeric band boundaries in named constants and derive the adjacent bound rather than typing both numbers. in 0..CAR_MAX followed by in CAR_MAX + 1..VAN_MAX cannot drift the way two hand-written literals can.
  • Keep each branch to a single expression or a single named call. If a branch needs a paragraph of work, that paragraph is a function, and lifting it out restores the when to showing the shape of the decision.
  • Drop the subject when the conditions test different things. A subject-less when is the idiomatic replacement for an if/else if chain, and it is clearer than inventing a subject or writing when (true).
  • Never let else mean two things. "Past the last band we listed" and "not a valid reading at all" deserve different branches and usually different types, because once they share a branch the program can no longer distinguish an expensive vehicle from a broken sensor.

Practice Exercises

  1. Fix the named flaw in the gate program. Declare enum class Band { CAR, VAN, HGV, SPECIAL }, change bandFor to return Band? with null for an implausible weight, and rewrite baseFor as an exhaustive when over Band with no else. Print the six crossings again, showing the minus-forty record as rejected rather than priced, and finish with a line reporting how many records were priced out of how many offered.
  1. Demonstrate order dependence deliberately. Write two functions with the same two overlapping range branches in opposite orders, choose one input for which they disagree and one for which they agree, print all four answers, and print a final line stating for each input whether the two functions agreed.
  1. Write surchargeFor twice, once as a when with an Int subject and once as a subject-less when using comparisons, then loop over the axle counts 1 through 9 printing the count and both answers on one line each. End with a line saying how many of the nine pairs agreed, and make sure it says nine.
  1. Replace the IntArray tally with a single fold whose accumulator is a Pair<Int, Int> and whose body is a when counting only the HGV and SPECIAL crossings. Print both counts, their sum and the row count, then print whether the remaining rows equal the number of CAR and VAN crossings you counted separately.