if as an expression in Scala
if/else evaluates to a value in Scala, so it can be assigned straight to a val.
val elevationGain = 820
// if/else is an expression, so it can be assigned to a val.
val grade =
if elevationGain < 300 then "easy"
else if elevationGain < 900 then "moderate"
else "strenuous"
// Both branches must agree on a type; here both are Int.
def restStops(gain: Int): Int =
if gain > 600 then 2 else 1
// Scala has no ternary operator because if already gives a value.
def waterLiters(hikers: Int, hot: Boolean): Double =
val perPerson = if hot then 2.0 else 1.25
hikers * perPerson
def hikePlan(): Unit =
println(s"$grade, ${restStops(elevationGain)} rest stops")
println(waterLiters(4, hot = true))
How it works
val grade =takes the result of anif elevationGain < 300 then "easy"chain that ends inelse "strenuous".def restStops(gain: Int): Intreturns a one-lineif gain > 600 then 2 else 1, where both branches areInt.- Inside
waterLitersthe localval perPerson = if hot then 2.0 else 1.25shows why Scala needs no ternary operator.
Keywords and builtins used here
BooleanDoubleIntUnitdefelsehikePlanifrestStopsthenvalwaterLiters
The run, in numbers
- Lines
- 20
- Characters to type
- 613
- Tokens
- 102
- Three-star pace
- 80 tpm
At the three-star pace of 80 tokens a minute, this run takes about 76 seconds.
Step 1 of 3 in Expressions, step 4 of 27 in Language basics.