KtKotlin
BeginnerLesson 3 of 16

Conditions: if and when – Kotlin

if as an expression and the powerful when.

In Kotlin, if is an expression and returns a value – that is why there is no ternary operator (? :). You can combine conditions with &&, ||, and !.

val punkte = 73
val note = if (punkte >= 90) "very good"
           else if (punkte >= 70) "good"
           else "needs improvement"
println(note)                       // good

val alter = 20
println(if (alter >= 18) "adult" else "minor")
println(punkte in 50..80)           // true

when replaces switch and can do much more: several values per branch, ranges (in), type checks (is). As an expression, it must cover all cases (else).

val tag = 6
val art = when (tag) {
    6, 7 -> "weekend"
    in 1..5 -> "weekday"
    else -> throw IllegalArgumentException("Invalid day: $tag")
}
println(art)                        // weekend

fun typ(x: Any) = when (x) {
    is Int -> "Int: ${x + 1}"          // smart cast: x is an Int here
    is String -> "String of length ${x.length}"
    else -> "other"
}
println(typ(41))                    // Int: 42
println(typ("Kotlin"))              // String of length 6

Without an argument, when simply checks a series of conditions – the first true one wins. A branch may be a block; the last expression is the value.

val temp = 22
val text = when {
    temp < 0 -> "freezing"
    temp < 15 -> "cool"
    temp < 25 -> {
        println("pleasant, computed")
        "warm"
    }
    else -> "hot"
}
println(text)                       // pleasant, computed / warm
WarningThere is no fall-through like in Java's old switch: only the first matching branch runs, and no break is needed.