This example shows how to match an input against several values:
def f(x: Int): String = x match {
case 1 => "One"
case 2 => "Two"
case _ => "Unknown!"
}
f(2) // "Two"
f(3) // "Unknown!"
Note: _
is the fall through or default case, but it is not required.
def g(x: Int): String = x match {
case 1 => "One"
case 2 => "Two"
}
g(1) // "One"
g(3) // throws a MatchError
To avoid throwing an exception, it is a best functional-programming practice here to handle the default case (case _ => <do something>
). Note that matching over a case class can help the compiler produce a warning if a case is missing. The same goes for user-defined types which extend a sealed trait. If the match is total then a default case may not be needed
It is also possible to match against values that are not defined inline. These must be stable identifiers, which are obtained by either using a capitalized name or enclosing backticks.
With One
and two
defined somewhere else, or passed as function parameters:
val One: Int = 1
val two: Int = 2
They can be matched against in the following way:
def g(x: Int): String = x match {
case One => "One"
case `two` => "Two"
}
Unlike other programming languages as Java for example there is no fall through. If a case block matches an input, it gets executed and the matching is finished. Therefore the least specific case should be the last case block.
def f(x: Int): String = x match {
case _ => "Default"
case 1 => "One"
}
f(5) // "Default"
f(1) // "Default"