if as an expression
The statement form of if looks like every C-family language: a condition in parentheses, a block, optional else if and else. The difference is that in Kotlin if is also an expression — it produces a value you can assign, return or pass to a function. The value of each branch is its last expression. That is why Kotlin has no condition ? a : b ternary operator: if (condition) a else b already does the job and reads as English.
fun main() {
val temperature = 31
// statement form
if (temperature > 30) {
println("Hot day")
} else if (temperature > 20) {
println("Warm day")
} else {
println("Cool day")
}
// expression form: the chosen branch is the value
val advice = if (temperature > 30) "Drink water" else "Enjoy"
println(advice)
val max = if (temperature > 25) {
println("checking a block branch")
temperature // last expression = the value
} else {
25
}
println("max = $max")
}Hot day
Drink water
checking a block branch
max = 31Set temperature to 18 and predict all four lines before you run it.
if used as an expression without else
fun main() {
val n = 5
val label = if (n > 0) "positive"
println(label)
}Main.kt:3:17: error: 'if' must have both main and 'else' branches when used as an expression.A value must exist on every path. If n were negative, the if would have nothing to produce, and label would have no value. The compiler refuses to guess.
Add an else branch. If there genuinely is no value in the other case, make the variable nullable and write else null.
fun main() {
val n = 5
val label = if (n > 0) "positive" else "not positive"
println(label)
}var x = "" and then set it inside each branch. val x = if (…) a else b is shorter, cannot be forgotten on one path, and keeps x read-only.