if Is an Expression
Every run in the logbook gets a label: "long run" or "easy run". In many languages you would declare an empty variable and then fill it inside an if. In Scala the if itself produces the label.
The rule
An if returns the value of the branch it takes.
val km = 8.5
val label = if km >= 10 then "long run" else "easy run"
// label is "easy run"In Scala 3 the shape is if condition then value else value. The older style, with parentheses and no then, still compiles and fills a lot of existing code: if (km >= 10) "long run" else "easy run".
A branch can be several lines long. Indent them, and the last expression of the branch is its value:
val message =
if km >= 10 then
val bonus = (km - 10) * 100
s"Long run! $bonus bonus metres"
else
"Easy run logged"Because if already returns a value, Scala has no ?: operator; it would add nothing.
An if with no else can only return Unit, because nothing is produced when the condition is false:
if km >= 10 then println("Long run!") // fine: used for its effect
val bonus: Int = if km > 20 then 5 // compile error: found Unit, required IntSo use if without else for actions, and if … then … else whenever you need a value. Try to make both branches give the same type, too; a String in one branch and an Int in the other gives a mixed type that is awkward to use.
The shortcut
Read every if as a question with two answers of the same type. If you cannot name the type both answers share, or one answer is missing, the value is not what you think it is.
Evaluate the condition
km >= 10with km = 8.5 is false.
The trap: writing var label = "" and assigning inside each branch. It works, but it adds a var and makes it easy to forget a branch. Assign the if itself.
Drills
Answer fast — trust the rule.
val label = if 12.0 >= 10 then "long run" else "easy run" — what is label?
What type does if km > 5 then println("far") have?
How do you write Java's ok ? "yes" : "no" in Scala 3?
What happens with val bonus: Int = if km > 20 then 5?
In a multi-line branch, which line gives the branch its value?
Remember
- An if is an expression:
if cond then a else breturns a or b. - Treat it as a question with two answers of the same type; the last line of a branch is its answer.
- Trap: an if without else is Unit, so it cannot produce a value.
