Scala Match Patterns
A match pattern describes the shape a value must have for a case to fit. Patterns can also add a condition, check a type, and pull values out of a larger value.
A guard adds a condition
The first case fits any number, but its guard also needs the number to be negative. The number -5 passes the guard.
@main def main(): Unit =
val number = -5
val label = number match
case n if n < 0 => "Negative"
case n if n == 0 => "Zero"
case _ => "Positive"
println(label)A type pattern names the value
The value holds text, so the String case fits. The name s can then be used in the result.
@main def main(): Unit =
val value: Any = "hello"
val label = value match
case s: String => s"Text with ${s.length} letters"
case i: Int => s"Number $i"
case _ => "Something else"
println(label)A case class pattern reads the fields
The pattern Point(x, y) fits the point and names its two fields. The result uses both names.
case class Point(x: Int, y: Int)
@main def main(): Unit =
val point = Point(3, 4)
val label = point match
case Point(x, y) => s"Right $x, up $y"
println(label)Example
case class Point(x: Int, y: Int)
@main def main(): Unit =
val pair = (7, "seven")
val label = pair match
case (n, word) => s"$word is $n"
println(label)
val point = Point(-2, 5)
val where = point match
case Point(x, y) if x < 0 => "Negative x"
case Point(x, y) => "On or right of zero"
println(where)Key points
- Guard: an extra if condition after a pattern that must also be true for the case to fit.
- Type pattern: a pattern like s: String that fits a value of that type and gives it a name.
- Any: the type that can hold a value of any type.
- Case class pattern: a pattern like Point(x, y) that fits a case class value and names its fields.
- Tuple pattern: a pattern like (n, word) that fits a tuple and names its parts.
- First fit wins: a value uses the first case whose pattern and guard both fit.
In this example, the tuple pattern names the parts of the pair, so the result prints seven is 7. The point pattern then names the fields of Point(-2, 5), and the guard sees that x is negative, so the first case wins.
Note
Put specific patterns before general ones, because a general case placed first wins every time.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Scastie
Exercise
Which case line uses a guard?