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:
Syntax
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
object Main extends App {
val day = 3
val name = day match {
case 1 => "Monday"
case 2 => "Tuesday"
case 3 => "Wednesday"
case _ => "Unknown"
}
println(name)
}
Login to try C/C++/Java/PHP code in the editor
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
- Leaving out the
case _ =>default, so an unmatched value throws aMatchErrorat runtime. - Using
breakor fall-through logic as in Java'sswitch, when eachcaseruns alone and does not fall through. - 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.
ifandmatchare expressions that produce values.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: