🎓 A1Learner
🔍
0 of 50 lessons completed

Scala If Expressions

An if expression is an if that gives back a value. That value can be stored in a val in one short line.

The block form repeats the same name

This form works, but the name label is written again in each branch. The next snippet shows a shorter way.

@main def main(): Unit =
  val score = 72
  var label = ""
  if score >= 50 then
    label = "Pass"
  else
    label = "Fail"
  println(label)

The value form stores the result once

The if sits on the right side of the val. It gives back one value, and that value is stored.

@main def main(): Unit =
  val score = 72
  val label = if score >= 50 then "Pass" else "Fail"
  println(label)

Number values work the same way

Each branch gives back a number here. The member flag picks which price is stored.

@main def main(): Unit =
  val member = true
  val guest = false
  val price = if member then 8 else 10
  val guestPrice = if guest then 8 else 10
  println(price)
  println(guestPrice)

Example

@main def main(): Unit =
  val age = 16
  val ticket = if age >= 18 then 12 else 7
  val group = if age >= 18 then "Adult" else "Teen"
  println(group)
  println(ticket)
  println(ticket * 2)

Key points

  • Value result: an if expression gives back the value from the branch that matches.
  • Stored once: the result is stored with one val and one name.
  • Single line: a short if expression fits on one line with then and else.
  • Else required: a value needs an else branch, so every case gives a value back.
  • Any type: the value can be a number, a string, or another type.

In this example, age is 16, so both if expressions take their else branch. The group is stored as Teen and the ticket price is stored as 7. Two tickets then cost 7 * 2, which is 14.

Note

both branches must give the same type of value.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Scastie

Exercise

What is stored in n? val n = if 3 > 5 then 1 else 2.