The when
expression is a versatile control flow statement in Kotlin. It serves as a more powerful and flexible alternative to the traditional switch statement found in many other programming languages.
The basic syntax of a when
expression is as follows:
when (expression) {
value1 -> result1
value2 -> result2
else -> defaultResult
}
The when
expression evaluates the given expression and compares it against the provided branches. When a match is found, the corresponding code block is executed.
One of the key features of Kotlin's when
is its ability to be used as an expression, returning a value:
val result = when (x) {
1 -> "x is 1"
2 -> "x is 2"
else -> "x is neither 1 nor 2"
}
println(result)
The when
expression allows you to check multiple conditions in a single branch:
when (x) {
0, 1 -> println("x is 0 or 1")
in 2..10 -> println("x is between 2 and 10")
else -> println("x is outside the range")
}
Kotlin's when
can also be used without an argument, functioning as a replacement for an if-else chain:
when {
x < 0 -> println("x is negative")
x == 0 -> println("x is zero")
else -> println("x is positive")
}
The when
expression works seamlessly with Kotlin's Smart Casts, allowing for type checking and casting in a single operation:
fun describe(obj: Any): String =
when (obj) {
is Int -> "It's an integer: $obj"
is String -> "It's a string of length ${obj.length}"
is List<*> -> "It's a list with ${obj.size} elements"
else -> "Unknown type"
}
when
instead of long if-else chains for improved readability.when
as an expression to write more concise code.else
branch to handle unexpected cases, unless you're certain all possible cases are covered.when
's ability to check multiple conditions in a single branch for more efficient code.To further enhance your understanding of Kotlin's control flow, explore these related topics:
By mastering the when
expression, you'll be able to write more expressive and concise Kotlin code, handling complex conditional logic with ease.