Kotlin

when Expressions — Powerful switch

admin by @admin ADMIN
just now
Jun 1, 2026
Public
0 0 up · 0 down Sign in to vote
Kotlin's `when` is an expression (returns a value), supports ranges, type checks, multiple values per branch, and arbitrary boolean conditions. Replaces nested if/else AND traditional switch.
Kotlin
Raw
fun classify(n: Int): String = when {
    n == 0          -> "zero"
    n in 1..9       -> "single digit"
    n in 10..99     -> "double digit"
    n < 0           -> "negative"
    n % 2 == 0      -> "even big number"
    else            -> "odd big number"
}

fun describe(x: Any): String = when (x) {
    is Int            -> "int $x"
    is String         -> "string of length ${x.length}"        // smart cast to String here
    is List<*>        -> "list of ${x.size} items"
    in 1..10          -> "small numberish"                       // works with operators
    null              -> "nothing"
    else              -> "unknown type ${x::class.simpleName}"
}

fun main() {
    for (n in listOf(0, 5, 42, -3, 100, 7)) println("$n → ${classify(n)}")
    for (x in listOf(7, "hi", listOf(1, 2, 3), null, 3.14)) println(describe(x))
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.