100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
Programming

Conditionals and Match Expressions

Understand how Scala treats if-else and match as expressions that return values, including pattern matching on case classes and sealed traits.

Functions & Control FlowBeginner9 min readJul 10, 2026
Analogies

Conditionals as Expressions, Not Statements

Unlike Java or C, where if is purely a control-flow statement with no value, Scala treats if-else as an expression: it evaluates to a value that can be assigned to a variable, passed as an argument, or returned from a function, such as val status = if (age >= 18) "adult" else "minor". This means the two branches must produce compatible types - the compiler infers a common supertype if they differ - and it eliminates the need for a separate ternary operator, since if-else already fills that role while remaining fully readable across multiple lines.

🏏

Cricket analogy: A third umpire's review doesn't just announce 'out' or 'not out' as a side effect - it produces a definitive result (the decision) recorded on the scoreboard, just as Scala's if-else produces a usable value rather than merely acting as a control step.

if-else Expressions and Type Unification

When the branches of an if-else return different types, Scala's type inference finds their least upper bound (LUB) so the whole expression still has a single, well-defined type; for example, if (cond) 1 else "one" unifies to Any, which is rarely useful and usually signals a design smell worth reconsidering. If an if has no else branch, its type is Unit, because the compiler must assume the condition could be false and no value is guaranteed, which is why omitting else in a value-producing position triggers a warning or type mismatch.

🏏

Cricket analogy: If a match has no result declared because rain washes it out, the official outcome defaults to 'no result' rather than a win for either side - just as an if without an else defaults to type Unit because no value is guaranteed.

scala
val temperature = 42
val advice =
  if (temperature > 40) "Heatwave: stay hydrated"
  else if (temperature > 25) "Warm day"
  else "Cool day"

println(advice)  // Heatwave: stay hydrated

Pattern Matching with match

The match expression generalizes switch statements into a powerful pattern-matching construct: a value is compared against a series of case patterns, each of which can match on literal values, types, wildcards (_), or destructured structures, and may include a guard clause like case n if n % 2 == 0 => "even". Because match is itself an expression, its result can be assigned directly, and Scala evaluates cases top-to-bottom, stopping at the first match, so pattern ordering - most specific before most general - matters for correctness.

🏏

Cricket analogy: A DRS review checks conditions in strict order - ball tracking first, then edge detection - stopping as soon as one rule conclusively decides the outcome, just as Scala's match checks cases top-to-bottom and stops at the first one that fits.

scala
def describe(x: Any): String = x match {
  case 0                => "zero"
  case n: Int if n < 0  => "negative int"
  case n: Int           => s"positive int: $n"
  case s: String        => s"a string of length ${s.length}"
  case _                => "something else"
}

Matching on Case Classes and Sealed Traits

match can destructure case classes directly in a pattern, binding their fields to new names in one step, such as case Point(x, y) => x + y for a case class Point(x: Int, y: Int). When the matched type is a sealed trait with a fixed, closed set of subtypes, the compiler performs exhaustiveness checking and warns if a match fails to cover every possible case, catching a whole category of bugs - like adding a new subtype and forgetting to handle it - at compile time instead of at runtime.

🏏

Cricket analogy: A rulebook defining every legal dismissal type (bowled, caught, LBW, run-out) is like a sealed trait - a scorer's decision logic must handle every listed type, and if a new dismissal type were added, every scoring system would need updating, just as the compiler flags a match missing a new sealed subtype.

Sealed traits plus exhaustive match expressions are Scala's answer to algebraic data types: because the compiler knows every possible subtype at compile time, it can statically verify that a match handles all of them, which is far safer than an open class hierarchy that any file could extend.

A non-exhaustive match on values outside a sealed hierarchy - such as matching on arbitrary Int values without a case _ fallback - compiles without error but throws a scala.MatchError at runtime if no case fits, so always include a wildcard case unless you are certain every possibility is covered.

  • if-else in Scala is an expression that returns a value, not just a control-flow statement.
  • If branch types differ, Scala infers their least upper bound (LUB) as the expression's type.
  • An if without an else has type Unit, since no value is guaranteed if the condition is false.
  • match evaluates cases top-to-bottom and stops at the first matching pattern, so ordering matters.
  • match can destructure case classes directly in a pattern, binding fields to new names.
  • Sealed traits enable compiler-checked exhaustiveness for match expressions covering all subtypes.
  • A non-exhaustive match on non-sealed types can throw a MatchError at runtime if no case fits.

Practice what you learned

Was this page helpful?

Topics covered

#Programming#ScalaStudyNotes#ConditionalsAndMatchExpressions#Conditionals#Match#Expressions#Not#StudyNotes#SkillVeris#ExamPrep