Skip to content
Kotlin

When Expression

Branch on values, ranges, and types with when as statement or expression.

By EZ4Code Team
whencontrol-flow

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