if Expressions
Prerequisites: Booleans and comparisons
@main def weather(): Unit =
val temperature = 18
if temperature > 25 then
println("It is hot")
else if temperature > 15 then
println("It is pleasant")
else
println("It is cold")
It is pleasant
Scala 3 writes if condition then ... else ..., with no parentheses
needed. (The Scala 2 style, if (temperature > 25) { ... }, still works.)
if returns a value
In Scala, if is an expression: it produces a value. There's no
separate ternary operator — you don't need one:
@main def status(): Unit =
val age = 20
val status = if age >= 18 then "adult" else "minor"
println(status)
val fee = if age < 12 then 5 else if age < 65 then 12 else 8
println(s"Ticket: $$$fee")
adult
Ticket: $12
($$ in an s string prints a literal dollar sign.)
Using if as an expression works naturally with val: the value is
decided once and never changes.
Common mistakes
- Leaving out the
elsewhen you use the result. Withoutelse, the missing branch produces()(Unit), so the value's type becomesAnyorUnit— rarely what you want.
Practice
Given an age, produce "adult" for 18 and over, "teen" for 13 to 17,
and "child" otherwise, as a single val.
Show solution
@main def ageGroup(): Unit =
val age = 15
val group =
if age >= 18 then "adult"
else if age >= 13 then "teen"
else "child"
println(group)
teen