When Expression
Branch on values, ranges, and types with when as statement or expression.
Code
// Basic when
fun describe(n: Int): String = when {
n < 0 -> "negative"
n == 0 -> "zero"
n in 1..10 -> "small"
n in 11..100 -> "medium"
else -> "large"
}
println(describe(5))
// When on subject
fun type(x: Any): String = when (x) {
is Int -> "int ${x.toString()}"
is String -> "string len=${x.length}"
is List<*> -> "list size=${x.size}"
else -> "unknown"
}
println(type(42))
println(type("hello"))
println(type(listOf(1, 2)))
// When with enum
enum class Direction { NORTH, SOUTH, EAST, WEST }
fun arrow(d: Direction) = when (d) {
Direction.NORTH -> "^"
Direction.SOUTH -> "v"
Direction.EAST -> ">"
Direction.WEST -> "<"
}
println(arrow(Direction.NORTH))
// When as a statement with blocks
val v = 3
when (v) {
1, 2 -> println("one or two")
in 3..5 -> {
println("three to five")
println("handled")
}
else -> println("other")
}
// Branch returns value
val label = when (v % 2) {
0 -> "even"
else -> "odd"
}
println(label)Explanation
when is Kotlin's switch replacement that works as both a statement and an expression. Branches can match values, ranges, types, or arbitrary boolean predicates, with no fall-through between them. When used on a sealed type or enum the compiler enforces exhaustiveness, catching missing cases at compile time.
More Kotlin Snippets
Null Safety
Use nullable types, safe calls, Elvis, and smart casts for null-safe code.
Data Classes
Model immutable data with auto-generated equals, copy, and destructuring.
Coroutines
Use launch, async, await, and structured concurrency with supervisorScope.
Extension Functions
Add methods to existing types with extensions and infix operators.
Sealed Classes
Model closed hierarchies and UI state with sealed classes and when.
Collections
Filter, map, group, partition, and chunk with functional operators.