Basic match
A basic match compares a value with a list of patterns and runs the first that fits, like a sorting hat placing each item in its house. It replaces long chains of ifs.
In this page:
Syntax
value match {
case pattern1 => result1
case pattern2 => result2
case _ => default_result
}
Basic match
A match expression compares a value against a sequence of case patterns, running (and producing the value of) the first one that matches.
case _ => acts as a catch-all default, and Scala warns (or errors, depending on settings) if a match isn't exhaustive for certain sealed types. Since match is an expression, its result can be assigned directly to a val.
Note:
Patterns are checked top to bottom, and only the first matching case runs -- order matters when patterns could overlap.
Example: Basic match
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
case _, so a value that matches nothing throws aMatchError. - Expecting
matchto fall through like Java'sswitch, when only the first matching case runs. - Writing
case day == 3 =>with a comparison, when a case takes a pattern, and conditions need a guard withif.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: