if as an Expression
In Kotlin, if is an expression that produces a value, so it replaces the ternary operator, and when it is used for a value it must have an else branch.
Use a conditional result in an assignment and inspect the resulting type.
The café's receipt should say "Thanks, regular!" for loyal customers and "Welcome!" for everyone else. In many languages you would declare a variable, then fill it in from two branches. In Kotlin, if itself hands back the answer.
The rule
if returns a value; with a value comes an else.
The familiar statement form still works:
if (cups >= 10) {
println("Free drink!")
}But if is also an expression: it produces the value of whichever branch runs.
val greeting = if (visits >= 10) "Thanks, regular!" else "Welcome!"This is why Kotlin has no ternary operator (cond ? a : b). An if on one line does the same job.
When a branch is a block { }, its value is the last expression in the block:
val price = if (isMember) {
println("Member discount applied")
3.5 * 0.9 // this is the value: 3.15
} else {
3.5
}Chains work with else if, checked from top to bottom; the first true condition wins:
val label = if (visits >= 10) "regular"
else if (visits >= 3) "returning"
else "new"When you use if for a value, the else is required. Without it, some paths would produce nothing, and the compiler rejects the code. As a plain statement, else is optional.