when with Ranges, Types and Conditions

Ranges in when

Example

Use in to match a range of values.

fun main() {
    val temperature = 33
    val advice = when (temperature) {
        in Int.MIN_VALUE..0 -> "Freezing"
        in 1..20 -> "Cold, take a jacket"
        in 21..30 -> "Pleasant"
        in 31..40 -> "Hot, stay hydrated"
        else -> "Heatwave alert"
    }
    println(advice)
}

Output

Hot, stay hydrated

Type Checks with is

Example

is checks the type, and inside the branch the value is smart-cast to that type.

fun describe(value: Any): String = when (value) {
    is Int -> "Int, doubled = ${value * 2}"
    is String -> "String of length ${value.length}"
    is Boolean -> if (value) "Yes" else "No"
    else -> "Something else"
}

fun main() {
    println(describe(21))
    println(describe("Kotlin"))
    println(describe(true))
    println(describe(3.5))
}

Output

Int, doubled = 42
String of length 6
Yes
Something else

when Without an Argument

Example

Without an argument, each branch is a full Boolean condition — a cleaner if-else if chain.

fun main() {
    val rating = 4.6
    val reviews = 1200
    val badge = when {
        rating >= 4.5 && reviews > 1000 -> "Top Rated"
        rating >= 4.0 -> "Highly Rated"
        reviews < 10 -> "New"
        else -> "Rated"
    }
    println(badge)
}

Output

Top Rated