Pattern matching
A match compares a value against patterns and runs the first branch that fits. It is an expression with a value, the compiler checks that the branches cover the type, and the patterns are far more than equality: a type test, a range guard, a list split into head and tail, or a value bound to a name for the branch that uses it.
Guards, alternatives and typed patterns
describe takes an Any and asks what it is. The order of the branches matters, because the first one that fits wins: the 0 branch comes before the general Int, and the guarded branch comes before the unguarded one:
matching.scala
def describe(value: Any): String = value match
case 0 => "zero"
case n: Int if n < 0 => s"negative $n"
case n: Int => s"positive $n"
case s: String if s.isEmpty => "empty text"
case s: String => s"text of ${s.length}"
case (a: Int, b: Int) => s"pair $a and $b"
case _ => "something else"
@main def matching(): Unit =
List(0, -3, 7, "", "scala", (1, 2), 2.5).foreach(value => println(describe(value)))
scala-cli run --server=false matching.scala
zero
negative -3
positive 7
empty text
text of 5
pair 1 and 2
something else
case n: Int if n < 0 is a typed pattern with a guard, and case (a: Int, b: Int) matches the shape of a pair as well as the types inside it. The last branch is a wildcard and catches every value the branches above it do not. A match over a closed type is checked instead: the compiler knows its cases, so a missed one is a warning and a wildcard would hide it.
A binding with @
A name before a pattern with @ binds the whole value while the pattern still takes it apart, and a list is matched from its ends with Nil and :::
binding.scala
def classify(values: List[Int]): String = values match
case Nil => "empty"
case head :: Nil => s"one value, $head"
case head :: tail => s"first $head, then ${tail.length} more"
def square(pair: (Int, Int)): String = pair match
case both @ (a, b) if a == b => s"$both is the square of $a"
case (a, b) => s"$a and $b differ"
@main def binding(): Unit =
println(classify(Nil))
println(classify(List(5)))
println(classify(List(1, 2, 3)))
println(square((4, 4)))
println(square((4, 5)))
val answer = List(1, 2, 3) match
case first :: _ => first * 10
case Nil => 0
println(answer)
scala-cli run --server=false binding.scala
empty
one value, 5
first 1, then 2 more
(4,4) is the square of 4
4 and 5 differ
10
both @ (a, b) gives the branch the pair and its halves at once, which saves a second destructuring line. head :: tail splits a list into its first element and the rest, and Nil is the empty list: the two patterns together cover every list. A match is also a value, so the last example assigns the branch it takes.
Related
- Sealed hierarchies: the types whose matches the compiler can check.
- Extractors: the unapply behind every pattern that is not a literal.
- Enums: matching on a case of an enum.
- Partial functions: the same patterns as a function value.
Автор статьи: Arthur Isaev