Junior
Explain the concept of 'when' expression in Kotlin programming language.
sobes.tech AI
Answer from AI
when in Kotlin is a versatile structural operator that replaces the traditional switch in other languages. It can be used as an expression (returning a value) or as a statement.
Main features:
-
Value comparison: Matching specific values.
fun describe(obj: Any): String = when (obj) { 1 -> "One" "Hello" -> "Greeting" is Long -> "Long" !is String -> "Not a string" else -> "Unknown" } -
Type check (
is/!is): Matching data types. -
Range or collection check (
in/!in): Checking inclusion in a range or collection.fun checkRange(x: Int): String = when (x) { in 1..10 -> "Positive number in range" !in 10..20 -> "Not in the second range" else -> "None of the above" } -
Without argument: Used as a more flexible replacement for a chain of
if-else if-else. Conditions are evaluated sequentially.fun checkBoolean(x: Boolean, y: Boolean): String = when { x && y -> "Both true" !x && !y -> "Both false" else -> "Mixed" } -
Return value: If
whenis used as an expression, it must be exhaustive (cover all possible cases or have anelsebranch).
when enhances code readability and safety compared to traditional switch.