if as an Expression
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.
The shortcut
Read an if expression as "this value, when …, otherwise that value". For chains, test the most demanding condition first, then check that the final else catches everything left over.
First condition
visits >= 10: 12 is at least 10, so this is true.
Drills
Answer fast — trust the rule.
What is val x = if (4 > 7) "yes" else "no"?
Why does val tip = if (total > 20) 2.0 fail to compile?
How do you write "a if cond else b" in Kotlin?
What is the value of if (true) { println("hi"); 5 } else { 0 }?
With visits = 5, what does if (visits >= 3) "returning" else if (visits >= 5) "loyal" else "new" give?
Remember
ifis an expression; it replaces the ternary operator.- A block's value is its last expression; a value-producing
ifneedselse. - In chains, the first true condition wins: most demanding first.
