Scala Else If
An else if chain checks conditions in order until one is true. Only the first true branch in the chain runs.
A grade chain picks one letter
The score is checked against each grade line in order. The second check is the first one that is true.
@main def main(): Unit =
val score = 85
if score >= 90 then
println("A")
else if score >= 80 then
println("B")
else if score >= 70 then
println("C")
else
println("D")The first true branch wins
A score of 95 passes the first three checks. Only one letter prints, which proves the later branches were skipped.
@main def main(): Unit =
val score = 95
if score >= 90 then
println("A")
else if score >= 80 then
println("B")
else if score >= 70 then
println("C")
else
println("D")The final else covers the rest
Zero is not above zero and not below zero. The chain falls through to the final else.
@main def main(): Unit =
val n = 0
if n > 0 then
println("Positive")
else if n < 0 then
println("Negative")
else
println("Zero")Example
@main def main(): Unit =
val marks = 73
if marks >= 90 then
println("A")
else if marks >= 80 then
println("B")
else if marks >= 70 then
println("C")
else if marks >= 60 then
println("D")
else
println("F")
println("Done")Key points
- Chain: a chain is a line of checks joined by else if.
- Order: the checks run from top to bottom, in the order written.
- First true wins: the first condition that is true picks the branch that runs.
- Else if: each else if adds one more condition and one more block.
- Final else: the last else runs when no earlier condition is true.
- Skipped checks: checks below the winning branch do not run.
In this example, marks is 73, so the first two checks are false and the third check is true. The chain prints C and skips the rest of the chain. The last line sits outside the chain, so Done prints after it.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Scastie
Exercise
In a grade chain for a score of 82, the checks are >= 90, then >= 80, then >= 70, then else. Which branch runs?