← Back to Scala Course | Chapter 3: Operators & Expressions | Lesson 7 of 7

match as an Expression

A match expression compares a value against several patterns and gives back the answer for the first one that fits, like sorting mail into the right slot. It is a more powerful cousin of a switch.

In this page:

  1. match as an Expression
Syntax
scala
val result = value match {
  case pattern1 => result1
  case pattern2 => result2
  case _        => default_result
}

match as an Expression

Scala's match expression compares a value against a series of patterns and, like if, produces a value rather than just performing a side effect.

It's more powerful than a typical switch statement, supporting type patterns, guards, and destructuring, covered in depth in a later chapter. Every match needs at least one case to handle, and a case _ wildcard is commonly used to handle anything not explicitly matched.

Note: case _ => acts as the default/catch-all branch, similar to default in a switch statement.

Example: match as an Expression

markup
object Main extends App {
  val day = 3

  val name = day match {
    case 1 => "Monday"
    case 2 => "Tuesday"
    case 3 => "Wednesday"
    case _ => "Unknown"
  }

  println(name)
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Leaving out the case _ => default, so an unmatched value throws a MatchError at runtime.
  2. Using break or fall-through logic as in Java's switch, when each case runs alone and does not fall through.
  3. Ordering cases wrongly, such as placing case _ first, so it catches everything and later cases are never reached.
Chapter Summary
  • Arithmetic, comparison, logical, and bitwise operators work with values.
  • String concatenation combines text.
  • if and match are expressions that produce values.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.