Kotlin by Example: When Expression
Replacing switch statements with this code example showing when expression for value matching, type checking with is operator, range checking with in operator, and when without argument for boolean conditions.
Code
fun describe(obj: Any): String {
return when (obj) {
1 -> "One"
"Hello" -> "Greeting"
is Long -> "Long number"
!is String -> "Not a string"
else -> "Unknown"
}
}
fun main() {
val x = 10
// when as a statement (no return value needed)
when {
x < 0 -> println("Negative")
x == 0 -> println("Zero")
x in 1..10 -> println("Between 1 and 10")
else -> println("Greater than 10")
}
println(describe(1))
println(describe("Hello"))
}Explanation
The when expression in Kotlin is a flexible and powerful replacement for the traditional switch statement found in languages like Java and C. It can be used both as an expression returning a value and as a statement for side effects. When used as an expression, the else branch is mandatory unless the compiler can prove all possible cases are covered, such as with enums or sealed classes.
When expression capabilities include:
- Matching constant values like numbers or strings
- Type checking with
isoperator, automatically smart-casting the variable - Range checking with
inoperator for inclusive ranges - Arbitrary boolean expressions when used without an argument
- Multiple conditions per branch separated by commas
Unlike switch statements, when does not require break statements as execution stops after the first matching branch. When used without an argument, it functions as a cleaner alternative to chained if-else if statements, with each branch condition being an independent boolean expression. The branches are evaluated sequentially until a match is found.
Code Breakdown
is Long type check with automatic smart cast to Long.x in 1..10 range check for inclusive range [1, 10].when { ... } without argument acts as if-else chain.when (obj) as expression returns value, no break needed.
