Basic match
In this page:
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
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: