when Expressions
The when expression is a significantly enhanced version of Java's switch statement. It supports not only value comparisons, but also type checks, range checks, and arbitrary condition expressions — and can return a value as an expression.
Syntax
// when expression with an argument.
when (value) {
pattern1 -> action or value
pattern2, pattern3 -> action or value
in range -> action or value
is Type -> action or value
else -> action or value
}
// when without an argument (write conditions directly).
when {
condition1 -> action
condition2 -> action
else -> action
}
Syntax Reference
| Syntax | Description |
|---|---|
| -> | Arrow that separates a pattern from its action. The right-hand side can also be a block. |
| pattern1, pattern2 | Multiple patterns separated by commas can share the same action. |
| in range | Checks whether the value is contained in the specified range or collection. |
| is Type | Performs a type check. After a match, smart cast is applied automatically. |
| else | Handles the case when no other pattern matches. Required when using when as an expression. |
Sample Code
fun main() {
val day = 3
// Basic when expression.
val dayName = when (day) {
1 -> "Monday"
2 -> "Tuesday"
3 -> "Wednesday" // day is 3, so "Wednesday" is selected.
4 -> "Thursday"
5 -> "Friday"
6, 7 -> "Weekend" // Multiple values can be grouped together.
else -> "Unknown"
}
println(dayName) // Prints "Wednesday".
// Range check example.
val score = 78
val grade = when (score) {
in 90..100 -> "A"
in 70..89 -> "B" // 78 falls in this range.
in 60..69 -> "C"
else -> "D"
}
println(grade) // Prints "B".
// Type check and smart cast example.
fun describe(obj: Any): String = when (obj) {
is Int -> "Int: ${obj * 2}" // obj is automatically used as Int.
is String -> "String: ${obj.length} chars"
is List<*> -> "List: ${obj.size} items"
else -> "Other"
}
println(describe(42)) // Prints "Int: 84".
println(describe("Kotlin")) // Prints "String: 6 chars".
// when without an argument (conditions written directly).
val temperature = 30
val comment = when {
temperature >= 35 -> "Extremely hot day."
temperature >= 30 -> "Very hot day." // This branch is selected.
temperature >= 25 -> "Hot day."
else -> "Comfortable temperature."
}
println(comment) // Prints "Very hot day.".
}
Notes
when is one of the most commonly used control flow constructs in Kotlin. When used as an expression, the else branch is required — unless all possible values are covered, such as with a sealed class or enum class, in which case the compiler allows it to be omitted. Combining when with a sealed class is especially powerful, as the compiler can detect missing branches at compile time.
For how to use when with sealed classes, see 'sealed class / sealed interface'. For details on ranges (in), see 'Ranges and for Loops'.
If you find any errors or copyright issues, please contact us.