Kotlin When
The when expression is Kotlin's replacement for the traditional switch statement, offering a cleaner syntax and far more matching power.
Basic when Syntax
A when block compares a subject value against a list of branches. As soon as a branch's value matches, its code runs and the rest of the branches are skipped — there is no fall-through, so you never need a break statement.
Basic when
fun main() {
val day = 3
when (day) {
1 -> println("Monday")
2 -> println("Tuesday")
3 -> println("Wednesday")
else -> println("Some other day")
}
}Combining Branches
Multiple values can share a single branch by separating them with commas. This avoids repeating the same body for related cases, such as grouping weekend days together.
Combined branches
fun main() {
val day = 6
when (day) {
1, 2, 3, 4, 5 -> println("Weekday")
6, 7 -> println("Weekend")
else -> println("Invalid day")
}
}when as an Expression
Just like if, when can be used as an expression that returns a value. In this form, the compiler requires the branches to be exhaustive — meaning every possible input must be covered, typically enforced with an else branch.
when as an expression
fun main() {
val statusCode = 404
val message = when (statusCode) {
200 -> "OK"
301 -> "Moved Permanently"
404 -> "Not Found"
500 -> "Server Error"
else -> "Unknown Status"
}
println(message)
}Ranges, Types, and Conditions in when
Kotlin's when is far more powerful than a typical switch. Branches can test ranges with in, check an object's type with is, or even omit the subject entirely and evaluate arbitrary Boolean conditions instead.
- Use in range to match a value falling within a range, such as 1..10.
- Use is Type to match based on runtime type, which also smart-casts the variable inside that branch.
- Omit the subject in when {} to write a chain of independent Boolean conditions, similar to else if.
Ranges and types
fun describe(input: Any): String {
return when (input) {
in 1..9 -> "Single digit number"
is String -> "A string of length ${input.length}"
is Boolean -> "A boolean value"
else -> "Something else"
}
}
fun main() {
println(describe(5))
println(describe("Kotlin"))
println(describe(true))
}Exercise: Kotlin When
Does Kotlin's when fall through to the next branch by default, like a C-style switch?