typestar

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

  1. val grade = takes the result of an if elevationGain < 300 then "easy" chain that ends in else "strenuous".
  2. def restStops(gain: Int): Int returns a one-line if gain > 600 then 2 else 1, where both branches are Int.
  3. Inside waterLiters the local val perPerson = if hot then 2.0 else 1.25 shows why Scala needs no ternary operator.

Keywords and builtins used here

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.

Type this snippet

Step 1 of 3 in Expressions, step 4 of 27 in Language basics.

← Previous Next →