Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 37 ยท Language Basics

Control Flow as Expressions

Learn Scala 3 control flow: if/then/else and match as expressions that return values, guards, the Unit result of if without else, and try/catch/finally.

In many languages, if and switch are statements: they do something but give nothing back. In Scala they are expressions, so they produce a value you can assign, return or pass. That removes a lot of temporary variables and mutation. This lesson covers if, match, try and a few smaller points, with runnable Java/Kotlin comparisons for the same logic.

if / then / else

SCALA
val temperature = 28

val label =
  if temperature > 30 then "hot"
  else if temperature > 15 then "warm"
  else "cold"

label is "warm". The whole if has a value, which is the value of the branch taken. That is why Scala has no ternary operator ?:: if ... then ... else ... already does the job.

In Scala 3 the then keyword replaces the parentheses. The old style still compiles:

SCALA
val label2 = if (temperature > 30) "hot" else "not hot"

if without else

Without an else, the missing branch has type Unit, so the expression is only useful for side effects:

SCALA
if temperature > 30 then println("Drink water")

Do not assign it: val x = if cond then 1 has type AnyVal (the common type of Int and Unit), which is almost never what you meant.

Types of branches

The type of the whole if is the nearest common supertype of its branches:

SCALA
val a = if true then 1 else 2.5      // Double
val b = if true then "x" else 1      // Any (probably a mistake)

Kotlin has the same expression-style if, which you can try:

Kotlin if as an expression (Kotlin comparison)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

match expressions

match compares a value against a series of patterns and returns the result of the first one that fits. For simple cases it works like a switch:

SCALA
def dayType(day: String): String =
  day match
    case "Sat" | "Sun" => "weekend"
    case "Mon" | "Tue" | "Wed" | "Thu" | "Fri" => "weekday"
    case other => s"unknown: $other"
  • | joins alternatives.
  • A bare name such as other matches anything and binds it.
  • _ matches anything without binding, so case _ => "?" is the default.
  • There is no fall-through: only one case runs, so no break is needed.

Guards

Add if after a pattern to refine it:

SCALA
def classify(n: Int): String =
  n match
    case 0 => "zero"
    case x if x < 0 => "negative"
    case x if x % 2 == 0 => "positive even"
    case _ => "positive odd"

classify(-5) is "negative" and classify(8) is "positive even".

Matching on types

Patterns can test the type of a value:

SCALA
def describe(x: Any): String =
  x match
    case i: Int => s"an Int: $i"
    case s: String => s"a String of length ${s.length}"
    case _: Double => "a Double"
    case _ => "something else"

match is far more powerful than switch. It also takes apart case classes, lists and tuples. Those richer patterns belong to the pattern-matching chapter, so here we stick to simple values.

If no case matches, a MatchError is thrown at runtime. For enum and sealed types the compiler warns about missing cases, which is a big safety win.

Java's modern switch expression is the closest relative. It is runnable:

Java switch expression in Java (comparison)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Blocks inside branches

A branch can be a multi-line block. The value of the block is its last expression:

SCALA
val message =
  if score >= 50 then
    val bonus = score - 50
    s"Pass with $bonus to spare"
  else
    "Fail"

try / catch / finally

try is an expression too. A failed operation can fall back to a value:

SCALA
def parseAge(text: String): Int =
  try text.toInt
  catch
    case _: NumberFormatException => -1

parseAge("42") is 42 and parseAge("abc") is -1. The catch block is a pattern match over the thrown exception. Add finally for clean-up code that always runs:

SCALA
try
  val data = readFile()
  process(data)
catch
  case e: java.io.IOException => println(s"IO problem: ${e.getMessage}")
finally
  println("done")

The result of the try is the value of the body or the matching catch case; the finally value is ignored.

Scala has no checked exceptions: you never have to declare or catch them. In practice, idiomatic code often uses Option, Either or Try instead of throwing, which we meet later.

throw

SCALA
def requirePositive(n: Int): Int =
  if n > 0 then n
  else throw IllegalArgumentException(s"not positive: $n")

throw has type Nothing, which fits every type, so the else branch is fine as an Int.

while loops (brief)

while exists, but it returns Unit and needs a var:

SCALA
var n = 3
while n > 0 do
  println(n)
  n -= 1

This prints 3, 2, 1. Most Scala code uses for or collection methods instead; see the next lesson.

Common mistakes

  • Forgetting then in Scala 3 when you omit parentheses.
  • Ending a match with no catch-all on a non-sealed type, which crashes with MatchError.
  • Using return inside a branch. Let the branch value flow out instead.
  • Writing a long if / else if chain where a match is clearer.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the Scala equivalent of the ternary operator condition ? a : b?

    if ... then ... else ... is an expression and returns a value, so Scala has no separate ternary.
  2. 2. What happens when no case of a match fits and there is no default?

    A non-exhaustive match that fails at runtime throws scala.MatchError.
  3. 3. Does match fall through to the next case like a C switch without break?

    Scala runs exactly one case, so there is no fall-through and no break.
  4. 4. What is the type of throw ...?

    throw never returns normally, so its type is Nothing, a subtype of every type.

Summary

  • if, match and try all produce values.
  • Use then in Scala 3 if; if without else returns Unit.
  • match supports alternatives with |, guards with if, type tests and binders; there is no fall-through.
  • try/catch/finally is an expression, and throw has type Nothing.
  • Prefer expressions over mutation; reserve while for rare cases.

Next: Loops and For Comprehensions