Explain it simply
Explain it simply
Every program has to choose. Show a welcome message to a returning visitor but a sign-up form to a new one, or charge a child fare, an adult fare or a senior fare. Kotlin gives you two tools for this: if for a two-way decision and when for picking one case out of many.
The part that surprises people coming from Java, C or JavaScript is that both are expressions. An expression is a piece of code that produces a value, so instead of declaring a variable and then assigning to it from inside each branch, you write val label = if (...) a else b. The variable is created, typed and filled in a single line, and you cannot forget to assign it on one path.
Problem → Why → Solution
The problem: the wrong branch quietly wins
Picture a report card. Marks of 90 and above get an A, 80 to 89 a B, and so on. Thinking aloud, you start with the widest idea, "any valid mark", and write 0..100 first. The program compiles and runs, but a student who scored 95 sees "Needs practice". Nothing crashes and no warning appears, so the bug can sit there until a real student complains.
fun main() {
val score = 95
val grade = when (score) {
in 0..100 -> "Needs practice" // matches every valid mark, so it always wins
in 90..100 -> "A" // never reached
in 80..89 -> "B" // never reached
else -> "Invalid mark"
}
println(grade) // Needs practice
}Why does the compiler not stop this?
A when checks its branches from top to bottom and stops at the first one that matches. The compiler does not compare your ranges with each other, so a wide range placed too early silently swallows every branch below it. Two related bugs do get caught: using if as an expression and forgetting else, and adding an enum value without updating a when over it. Kotlin turns both into compile errors, which is a good reason to prefer the expression forms.
Core concept: if and when produce values
In Kotlin, if is an expression. When you put it on the right of a val or after return, the value of the branch that runs becomes the value of the whole if. If a branch is a { } block, the last expression inside it is the value, so no return keyword is needed. There is no ternary operator (a ? b : c) because if already does that job. The result has to exist on every path, so an if used as an expression must have an else. Writing val result = if (score >= 50) "Passed" makes kotlinc answer: 'if' must have both main and 'else' branches when used as an expression.
when is the multi-way version. It takes a subject, compares it with each branch condition from top to bottom, and runs the first branch that matches. A condition can be a constant (3), several constants separated by commas (6, 7), a range test (in 90..100), a type test (is String), or, if you leave the subject out, any boolean expression. Branches use an arrow (->), there is no break, and nothing falls through: only one branch ever runs.
Used as an expression, a when must be exhaustive, meaning every possible subject value needs a branch. For an Int or String subject the compiler cannot know all the values, so you finish with an else. For an enum (and for the sealed types you will meet later) the compiler knows every case, so listing them all is enough and else becomes optional. That is more useful than it sounds: add a new enum entry later and every when over it that lacks the branch stops compiling, which gives you a to-do list from the compiler. Kotlin 2.1 even rejects a when statement over an enum if a case is missing.
| Form | Use it for | Needs else? |
|---|---|---|
| if (cond) a else b | A two-way choice | Yes, when used as a value |
| when (x) { 1 -> ... } | One subject compared with many cases | Yes, unless every enum or sealed case is listed |
| when { cond -> ... } | Independent conditions checked in order | Yes, when used as a value |
- Evaluate the condition or subject
- Test branches from the top down
- First match runs, the rest are skipped
- The branch's last value is the result
Order matters: put the narrow cases first and the catch-all else last.
General pattern
val result = if (condition) valueA else valueB
val result = when (subject) {
constant, otherConstant -> valueA
in range -> valueB
is Type -> valueC
else -> fallback
}The first form is a two-way choice and the second compares one subject with constants, ranges and types. Drop the subject and write when { condition -> value } to check boolean conditions in order instead. Each form produces a value that can go straight into a val.
Example: grading a single mark
This program grades one score three ways: a one-line if expression for pass or fail, a when over ranges for the letter, and an if whose block body ends with the value. Try to predict the output before running it: what does a score of 82 produce?
fun main() {
val score = 82
val result = if (score >= 50) "Passed" else "Failed"
println(result)
val grade = when (score) {
in 90..100 -> "A"
in 80..89 -> "B"
in 70..79 -> "C"
else -> "Needs practice"
}
println("Grade: $grade")
val message = if (score >= 80) {
val bonus = score - 80
"Merit, $bonus points above the bar"
} else {
"Keep practising"
}
println(message)
}Code breakdown
- if as a value
val result = if (score >= 50) "Passed" else "Failed"The result of the if goes straight into result. 82 >= 50 is true, so the value is "Passed" and Kotlin infers String. Remove the else and it no longer compiles.
- Range branch
in 80..89 -> "B"in 80..89 asks whether score lies between 80 and 89, both ends included. 82 misses the first branch (90..100) and matches this one, so the value is "B" and the branches below are never tested.
- Catch-all
else -> "Needs practice"You cannot list every possible Int, so else catches whatever is left. A when used as an expression without it does not compile.
- Block with a value
val bonus = score - 80A block branch can hold several statements. This line creates a local variable, bonus, that exists only inside that branch.
- Last expression
"Merit, $bonus points above the bar"The last expression of the block is the value of the whole if, so no return is needed. The string template swaps in 2 for $bonus, giving "Merit, 2 points above the bar".
Passed
Grade: B
Merit, 2 points above the bar- score is 82
- Is it in 90..100? No
- Is it in 80..89? Yes
- Produce "B" and skip the remaining branches
A branch matches
Run it and use its value
Nothing matches
else runs, or compile error if else is missing
Commas, is checks and a when with no subject
Several conditions separated by commas in one branch mean "run this if any of them matches". An is Type -> branch checks the subject's type, and inside a matching branch you can use the value as that type without a cast (a smart cast). In describe() below, value.length is only legal inside the is String branch.
A when { } with no subject is a tidier way to write a long else if chain. Every branch is its own boolean condition and the first true one runs. Notice that band() counts down from 90. Thresholds also stay correct if you later move from whole numbers to decimals, where a range such as in 80..89 would leave 89.5 uncovered.
fun describe(value: Any): String = when (value) {
0, 1 -> "tiny number"
is Int -> "int, next is ${value + 1}"
is String -> "text of length ${value.length}"
else -> "something else"
}
fun band(score: Int): String = when {
score >= 90 -> "A"
score >= 80 -> "B"
score >= 70 -> "C"
else -> "Needs practice"
}
fun main() {
println(describe(1))
println(describe(41))
println(describe("kotlin"))
println(describe(2.5))
println(band(95))
println(band(80))
println(band(12))
}The output is tiny number, int, next is 42, text of length 6, something else, and then A, B, Needs practice. describe(1) stops at the first branch (0, 1) and never reaches is Int, which is branch order at work again.
An exhaustive when over an enum
When a thing has only a few possible states, such as an order status, an enum class plus a when lets you handle every case with no else. The code below has no else, yet it compiles because all three cases are covered. Status.entries returns every case of the enum as a list.
enum class Status { PENDING, SHIPPED, DELIVERED }
fun label(status: Status): String = when (status) {
Status.PENDING -> "Waiting for the warehouse"
Status.SHIPPED -> "On the way"
Status.DELIVERED -> "At your door"
}
fun main() {
for (status in Status.entries) {
println("$status -> ${label(status)}")
}
}Now add a case
Add CANCELLED to the enum without touching label() and kotlinc 2.1.21 reports: 'when' expression must be exhaustive. Add the 'CANCELLED' branch or an 'else' branch. That is a good error: it points at exactly what to fix. If you silence it with else -> ..., the next case you add will no longer be flagged.
In real projects
Where this shows up in real projects
Backend code uses when to map an HTTP status code to an error category, to turn order and payment states into user-facing text, and to choose a price tier from an age, a weight or an order size. In Android apps, a screen state such as loading, success or error is often a sealed type, and a when decides what to draw.
The expression style also pays off in code review. A single val label = when (status) { ... } shows every possible value of label in one place, which reads better than declaring var label = "" and assigning in each branch, and the compiler catches a branch that forgot to assign. Many teams deliberately write when over enums and sealed types without an else, because when the model gains a case the compiler finds every piece of code that needs updating.
Common mistakes
Common mistakes
1. Writing the widest range first
Putting in 0..100 above in 90..100 sends even 95 to the first branch. The compiler gives no warning, so order branches from narrowest to widest, or use a subject-less when with >= thresholds from highest to lowest. When you test, check the boundary values (90, 89, 0).
2. Forgetting the else of an if expression
val result = if (score >= 50) "Passed" does not compile: 'if' must have both main and 'else' branches when used as an expression. A long else if chain with no final else is the same problem. If you do not need a value and only want a side effect such as printing, write the if as a statement and the else becomes optional.
3. Adding else to an enum when and switching off the check
Adding else -> "Unknown" to make the error go away means the next enum entry you add will no longer be flagged anywhere and will quietly land in "Unknown". Over an enum or a sealed type, write out every case yourself and keep else for values that really cannot be known, such as input from outside.
Best practices
Best practices
- When the goal is one value, prefer val x = if/when over a var plus assignments, so the variable cannot change and every branch must supply a value.
- Once you have three or more conditions, switch from an else if chain to when.
- Do not add else to a when over an enum or sealed type; let the compiler tell you where to update when a case is added.
Mini challenge
Mini challenge: a shipping fee calculator
Write a parcel shipping calculator. Model the destination zone as an enum, pick the base price with a when that has no else, label the weight class, and add a surcharge for heavy parcels.
- enum class Zone with LOCAL, REGIONAL and INTERNATIONAL
- shippingFee(zone, weightKg) picks the base price 5, 12 or 30 with a when that has no else, then adds 15 when the weight is over 20
- weightClass(weightKg) uses a subject-less when to return invalid (under 1), light (up to 5), standard (up to 20) or heavy
- main prints the weight class and the fee for LOCAL 3 kg, REGIONAL 12 kg and INTERNATIONAL 25 kg
enum class Zone { LOCAL, REGIONAL, INTERNATIONAL }
fun weightClass(weightKg: Int): String {
// TODO: subject-less when, thresholds from smallest to largest
}
fun shippingFee(zone: Zone, weightKg: Int): Int {
// TODO: val base = when (zone) { ... } with no else
// TODO: val surcharge = an if expression for weights over 20
// TODO: return the sum
}
fun main() {
// TODO: print "<class>: <fee>" for (LOCAL, 3), (REGIONAL, 12), (INTERNATIONAL, 25)
}Expected: light: 5 standard: 12 heavy: 45
Show hint
Start weightClass() with weightKg < 1 -> "invalid", then weightKg <= 5 and weightKg <= 20 in increasing order. Leave else out of the when over zone: with all three cases listed the compiler accepts it.
Show solution
enum class Zone { LOCAL, REGIONAL, INTERNATIONAL }
fun weightClass(weightKg: Int): String = when {
weightKg < 1 -> "invalid"
weightKg <= 5 -> "light"
weightKg <= 20 -> "standard"
else -> "heavy"
}
fun shippingFee(zone: Zone, weightKg: Int): Int {
val base = when (zone) {
Zone.LOCAL -> 5
Zone.REGIONAL -> 12
Zone.INTERNATIONAL -> 30
}
val surcharge = if (weightKg > 20) 15 else 0
return base + surcharge
}
fun main() {
println("${weightClass(3)}: ${shippingFee(Zone.LOCAL, 3)}")
println("${weightClass(12)}: ${shippingFee(Zone.REGIONAL, 12)}")
println("${weightClass(25)}: ${shippingFee(Zone.INTERNATIONAL, 25)}")
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- if and when are expressions, so a value can go straight into a val, and then an else (or every case) is mandatory.
- when checks branches from the top down and runs only the first match, so put narrow cases first.
- Ranges, type checks, commas and the subject-less form make when very flexible.
- A when over an enum or sealed type with no else turns a newly added case into a compile error.
Kotlin language guide — Kotlin