iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

if / when

Kotlin’s if, when, and loops are all expressions — they return values. when replaces both switch and big if/else chains; you reach for it everywhere.

if-as-expression, when, ranges

EXAMPLE
fun main() {
    val age = 36

    // 1) if as expression
    val tier = if (age >= 65) "senior"
               else if (age >= 18) "adult"
               else "minor"
    println(tier)

    // 2) when — replaces switch / big if-else
    val label = when (tier) {
        "senior" -> "Senior pricing"
        "adult"  -> "Standard pricing"
        "minor"  -> "Free entry"
        else     -> "Unknown"
    }

    // 3) when without a subject — pure boolean dispatch
    val grade = when {
        score >= 90 -> "A"
        score >= 80 -> "B"
        score >= 70 -> "C"
        else        -> "F"
    }

    // 4) when over ranges + types
    val obj: Any = "hello"
    val description = when (obj) {
        in 1..9      -> "single digit"
        in 10..99    -> "double digit"
        is String    -> "string of length ${obj.length}"
        is Int       -> "int $obj"
        null         -> "null"
        else         -> "other"
    }

    // 5) when with multiple labels per branch
    when (day) {
        "Sat", "Sun"                            -> println("weekend")
        "Mon", "Tue", "Wed", "Thu", "Fri"        -> println("weekday")
    }

    // 6) Loops
    for (i in 0 until 5) println(i)        // 0..4 exclusive
    for (i in 5 downTo 1 step 2) println(i) // 5, 3, 1
    for ((k, v) in mapOf("a" to 1, "b" to 2)) println("$k=$v")
}

Why it matters

Most modern Kotlin code uses when as the only branching primitive — even for simple two-branch conditionals. Treat when as a tiny pattern-matching DSL and your code reads cleaner.

Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.

Example

Example
val msg = if (n > 0) "positive" else "non-positive"

val kind = when (n) {
    0 -> "zero"
    in 1..9 -> "digit"
    else -> "big"
}
Try it Yourself »

Discussion

Loading…