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.
val temperature = 42
val advice =
if (temperature > 40) "Heatwave: stay hydrated"
else if (temperature > 25) "Warm day"
else "Cool day"
println(advice) // Heatwave: stay hydratedPattern 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.
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
1. What does `val status = if (age >= 18) "adult" else "minor"` demonstrate about Scala's if-else?
2. What is the type of `if (temp > 30) 1 else "cold"` in Scala?
3. What is the type of an if expression that has no else branch?
4. In match, what happens if a case has a guard like `case n if n % 2 == 0 => ...`?
5. What does the compiler do when a match on a sealed trait fails to cover all subtypes?
Was this page helpful?
You May Also Like
Functions in Scala
Learn how to define, call, and structure functions in Scala using def, including default parameters, named arguments, and multiple parameter lists.
Loops and For-Comprehensions
Explore Scala's imperative loop constructs alongside the functional for-comprehension, including guards, nested generators, and yield-based transformations.
Higher-Order Functions
Learn how Scala functions that accept or return other functions enable powerful, reusable abstractions like map, filter, fold, and currying.
Related Reading
Related Study Notes in Programming
Browse all study notesApache Spark Study Notes
Programming · 30 topics
ProgrammingApache Flink Study Notes
Programming · 30 topics
ProgrammingHadoop Study Notes
Programming · 30 topics
ProgrammingSnowflake Study Notes
Programming · 30 topics
ProgrammingApache Airflow Study Notes
Programming · 30 topics
Programmingdbt (Data Build Tool) Study Notes
Programming · 30 topics