How does the 'when' construct work in Kotlin?
sobes.tech AI
Answer from AI
The when construct in Kotlin is a flexible replacement for the switch operator in other languages. It allows matching a value against various branches (conditions) and executing the corresponding block of code. when can be used either as an expression (returning the value of the last line of the executed branch) or as a statement (simply executing code).
Main features:
-
Matching constant values: Checking for equality with literals, constants, or other immutable values.
// Example of matching constants fun describe(obj: Any): String = when (obj) { 1 -> "One" "Hello" -> "Greeting" is Long -> "Long" !is String -> "Not a string" else -> "Unknown" } -
Type matching (
is,!is): Checking whether an object is an instance of a specific type (or not). If matched, the variable in the branch is automatically cast to the specified type (smart cast). -
Matching by ranges and collections (
in,!in): Checking whether a value falls within a range or collection.// Example of range matching fun isHot(temperature: Int): Boolean = when (temperature) { in 30..100 -> true else -> false } -
Multiple conditions in one branch: Multiple expressions can be combined with commas in a single branch. If at least one expression is true, the branch executes.
// Example of multiple conditions in one branch fun getColorName(rgb: Int): String = when (rgb) { 0xFF0000, 0xFF0001, 0xFF0002 -> "Red variant" 0x00FF00 -> "Green" 0x0000FF -> "Blue" else -> "Unknown" } -
Using arbitrary expressions: Each branch can contain an arbitrary boolean expression.
// Example with arbitrary expressions fun evaluate(score: Int): String = when { score >= 90 -> "Excellent" score >= 75 -> "Good" score >= 60 -> "Satisfactory" else -> "Poor" }In this case,
whenis used without an argument. The branch conditions are evaluated sequentially until one becomes true. -
elsebranch: Theelsebranch should be used to handle all other cases not covered by previous branches. It is mandatory ifwhenis used as an expression, and the compiler cannot prove that all possible cases are handled. -
Order of execution: Branches are checked sequentially from top to bottom. As soon as the first matching branch is found, its code is executed, and
whenterminates (or returns a value).
The when construct is more expressive and safer compared to traditional switch, as it supports more complex conditions and requires handling all possible cases (or using else), preventing potential errors.