TExcelTAD
Home › Scala › Scala If Expressions

Scala If Expressions

if lets your program choose between alternatives. In Scala, if is an expression: it produces a value. That small detail removes the need for the ? : ternary operator found in C-family languages and makes code shorter and safer.

The basic form

Scala 3 writes the condition without parentheses and uses then:

scala · try it yourself
@main def run(): Unit =
  val stock = 3
  if stock == 0 then
    println("Sold out")
  else if stock < 5 then
    println(s"Only $stock left — hurry!")
  else
    println("In stock")
Only 3 left — hurry!

The classic Scala 2 form with parentheses and braces still compiles: if (stock == 0) { … } else { … }.

if as an expression

Because if returns a value, you can assign its result directly. Both branches should produce the same type (or the compiler picks their common supertype).

scala · try it yourself
@main def run(): Unit =
  val age = 17
  val ticket = if age < 18 then "junior" else "adult"
  val price = if age < 18 then 6.5 else 11.0
  println(s"$ticket ticket costs $price")

  val parity = if age % 2 == 0 then "even" else "odd"
  println(s"$age is $parity")
junior ticket costs 6.5
17 is odd

Tip: Prefer val result = if … then … else … over declaring a var and assigning it in each branch. The value is computed in one place and can never be changed by accident.

One-line and block branches

A branch can be a single expression on the same line or an indented block. The block's last expression is the branch's value.

scala · try it yourself
def shippingCost(weightKg: Double, express: Boolean): Double =
  if express then
    val base = 9.0
    base + weightKg * 2
  else if weightKg <= 1 then 0.0
  else 4.5

@main def run(): Unit =
  println(shippingCost(0.5, express = false))
  println(shippingCost(3.0, express = false))
  println(shippingCost(3.0, express = true))
0.0
4.5
15.0

if without else

An if with no else has type Unit: it is only useful for its side effect, such as printing.

scala · try it yourself
@main def run(): Unit =
  val warnings = List("low battery", "no network")
  if warnings.nonEmpty then println(s"${warnings.size} warnings")
  val value = if warnings.isEmpty then println("all good")
  println(value)
2 warnings
()

The second if has no else, so its type is Unit; because the condition is false, its value is (), the only value of type Unit. (If the branch produced, say, an Int, the compiler would warn that the value is discarded.)

Combining conditions

Use &&, || and ! to build bigger conditions:

scala · try it yourself
@main def run(): Unit =
  val hour = 22
  val isWeekend = true
  val musicAllowed = (hour >= 8 && hour < 22) || (isWeekend && hour < 23)
  println(if musicAllowed then "Play on" else "Quiet hours")

  val name = ""
  if !name.isBlank then println(s"Hello $name")
  else println("Hello, stranger")
Play on
Hello, stranger

if vs. match

When you compare one value against many possibilities, a match expression (next chapter) is usually clearer than a long if … else if chain.

Use if when… Use match when…
you test unrelated conditions you compare one value against many cases
there are two or three branches you need to take data apart (patterns)
conditions are ranges or combinations cases are constants, types or shapes

Common mistakes

Mistake Fix
if x = 5 then … use == to compare: if x == 5 then …
forgetting else and expecting a value add an else branch so the type is not Unit
branches of very different types the result becomes Any; make both branches return the same type
mixing then with parentheses-only style badly pick either if cond then or if (cond)

Test yourself

What is the type of if x > 0 then "positive" else "other"?

  1. Boolean
  2. Unit
  3. String
  4. Any

What value does if false then 42 produce?

  1. 0
  2. null
  3. ()
  4. 42

Does Scala have a cond ? a : b ternary operator?

  1. Yes, exactly like Java
  2. No, if cond then a else b is already an expression
  3. Only for numbers
  4. Only in Scala 2