else if Chains
Two labels are not enough. The club wants four: "rest day", "easy run", "long run", and "half marathon" for anything from 21.1 km. Chaining conditions is easy to type; putting them in the right order is the real skill.
The rule
Tests run top to bottom and the first true one wins, so the strictest goes first.
val label =
if km >= 21.1 then "half marathon"
else if km >= 10 then "long run"
else if km > 0 then "easy run"
else "rest day"- Scala checks each condition in order and stops at the first that is
true. Later conditions are never looked at. - Each
else ifcan rely on everything above it being false. By the time thekm > 0test runs, you already knowkmis under 10. - The final plain
elsecatches whatever is left, so the chain has a value in every case. Without it, the whole chain would beUnit. - Every branch should give the same type, here a
String.
The braces style works too, and you will see it in Scala 2 code:
val label = if (km >= 21.1) { "half marathon" } else if (km >= 10) { "long run" } else { "easy run" }When every test compares the same value against a number, the chain reads like a ladder of thresholds. Keeping the rungs in order is what the shortcut below is for.
The shortcut
Line the thresholds up on a number line and write them from the strictest to the loosest: when testing with >=, the highest threshold goes first. Then read the chain aloud, saying "otherwise" for each else.
First test
25 >= 21.1is true. The label is "half marathon" and the chain stops.
The trap is exactly that dead branch. The compiler will not warn you, because the code is perfectly valid; only the ordering rule protects you.
Drills
Answer fast — trust the rule.
Using the chain above, what label does a 10.0 km run get?
And what does a 0.0 km day get?
If the km >= 10 test is moved above km >= 21.1, what does a 30 km run get?
Why end the chain with a plain else?
By the time the km > 0 test runs in the chain above, what do you already know?
Remember
- Tests run top to bottom and the first true one wins; each later branch knows the earlier tests failed.
- Order thresholds from strictest to loosest, and end with a plain
else. - Trap: a loose test placed early makes later branches unreachable, with no compiler warning.
