when in Kotlin
The switch that matches ranges, lists of values, and bare conditions.
fun main() {
val windKmh = 38
// when replaces switch; ranges and commas both guard a branch.
val flag = when (windKmh) {
in 0..11 -> "calm"
in 12..29 -> "breezy"
30, 31 -> "gusty"
else -> "stay off the ridge"
}
println("Wind $windKmh km/h: $flag")
// Without a subject, each branch is a full condition.
val season = "fall"
when {
season == "winter" -> println("Hut stove is lit")
else -> println("Cold water only")
}
}
How it works
when (windKmh)tests the subject against each branch in order.in 0..11matches a range;30, 31matches either value;elsecatches the rest.- A subjectless
whenchains full boolean conditions like an if ladder.
Keywords and builtins used here
elsefuninmainvalwhen
The run, in numbers
- Lines
- 18
- Characters to type
- 420
- Tokens
- 102
- Three-star pace
- 70 tpm
At the three-star pace of 70 tokens a minute, this run takes about 87 seconds.
Step 2 of 3 in Control flow, step 5 of 27 in Language basics.