Scala If Else
An if statement runs a block of lines only when its condition is true. An else block runs when the condition is false.
The if block runs when the condition is true
The age is 20, so the condition is true. Only the first block prints.
@main def main(): Unit =
val age = 20
if age >= 18 then
println("Adult")
else
println("Minor")The else block runs when the condition is false
The temperature is 15, so the condition is false. Only the else block prints.
@main def main(): Unit =
val temp = 15
if temp > 25 then
println("Hot")
else
println("Cool")A string condition picks a block
A comparison on text can be the condition too. The day matches, so the if block prints.
@main def main(): Unit =
val day = "Sat"
if day == "Sat" then
println("Weekend")
else
println("Weekday")Example
@main def main(): Unit =
val battery = 15
if battery < 20 then
println("Low battery")
println("Charge soon")
else
println("Battery fine")Key points
- Condition: the condition is a Boolean value that is true or false.
- Then: the word then marks the end of the condition line in Scala 3.
- Block: a block is a group of indented lines that belong together.
- If block: the indented lines under if run only when the condition is true.
- Else block: the indented lines under else run only when the condition is false.
- One branch: exactly one of the two blocks runs each time.
In this example, battery is 15, so battery < 20 is true. Both indented lines in the if block run, printing Low battery and then Charge soon. The else block does not run.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Scastie
Exercise
What does this code print? val score = 40, then if score >= 50 then println("Pass") else println("Fail").