Part 04 / Topic 3 of 8
when without a subject
Drop the thing in parentheses, and every branch becomes its own Boolean condition, checked top
to bottom until one is true — the same shape as a long if/else if/else if/else chain, written
without repeating if/else if on every line.
val temp = 41
val advice = when {
temp >= 40 -> "Heatwave -- stay indoors"
temp >= 30 -> "Hot -- carry water"
temp >= 20 -> "Pleasant"
else -> "Cold -- carry a jacket"
}
println(advice)
Heatwave -- stay indoors
Because there's no single subject being compared, branches are free to mix completely unrelated
conditions — something a subject when can't do, since every branch there has to compare against the
same one value:
val city = "Mumbai"
val note = when {
city == "Mumbai" && temp >= 30 -> "Humid heat"
city == "Delhi" && temp >= 40 -> "Dry heat"
city == "Bengaluru" -> "Usually mild, check anyway"
else -> "No special note"
}
println(note)
Humid heat
A subject-less when works as a statement too, the same top-to-bottom check, just printing
directly instead of producing a value:
val score = 67
when {
score >= 90 -> println("Topper")
score >= 60 -> println("Comfortable pass")
score >= 40 -> println("Pass")
else -> println("Fail")
}
Comfortable pass
Reach for the subject form (section 2) when you're really comparing one value against several options; reach for this subject-less form when the branches are independent conditions that don't share a single thing being compared.
Full program: examples/03_when_without_subject.kt.
Done here? The practice set for Part 4 — including the solutions — is on the part page.