if & when Expressions
if is an expression
val max = if (a > b) a else b // no ternary operator needed
val grade = if (score >= 90) "A" else if (score >= 75) "B" else "C"
In a block, the last line is the value.
when: a powerful switch
val label = when (day) {
"Sat", "Sun" -> "Weekend"
"Mon" -> "Ugh, Monday"
else -> "Weekday"
}
when can match:
- values:
1, 2 -> - ranges:
in 90..100 -> - types:
is String ->(with a smart cast inside) - any condition, with no argument at all:
when {
temp < 0 -> "Freezing"
temp < 20 -> "Cool"
else -> "Warm"
}
When used as an expression, when must be exhaustive (cover every case). With enum and sealed classes, the compiler checks this for you (Unit 5).
Smart casts
After a type check, Kotlin treats the variable as that type automatically:
if (x is String) println(x.length) // no cast needed
Comparisons
== compares content (like Java's .equals()); === compares references. So "hi" == "hi" is true in Kotlin.
Example
fun describe(x: Any): String = when (x) {
0 -> "zero"
in 1..9 -> "a small number"
is Int -> "a big number"
is String -> "text of length ${x.length}" // smart cast to String
is List<*> -> "a list with ${x.size} items"
else -> "something else"
}
fun main() {
val a = 7; val b = 12
val max = if (a > b) a else b
println("max = $max")
for (score in listOf(95, 80, 60)) {
val grade = when {
score >= 90 -> "A"
score >= 75 -> "B"
else -> "C"
}
println("$score → $grade")
}
listOf<Any>(0, 5, 500, "Kotlin", listOf(1, 2), 3.5).forEach { println("$it is ${describe(it)}") }
println("hi" == "hi") // true — content equality
}