Scala unapplySeq extractor syntax

711 views Asked by At

I (inadvertently) came across a bit of pattern matching syntax I did not expect to compile and now cannot figure out.

It appears related to unapplySeq.

Note the case x List(_,_) part in this simple example:

val xs = List(1, 2, 3)                          //> xs  : List[Int] = List(1, 2, 3)

xs match {
    case x List (_, _) => "yes"
    case _             => "no"
}                                               //> res0: String = yes

I am used to : or @ in pattern match syntax, but am confused about this. How does this syntax work and what (if any) is its relationship to unapplySeq?

Sample code executed in Scala 2.11.6

1

There are 1 answers

9
bjfletcher On BEST ANSWER

The equivalent non-infix version is:

xs match {
  case List(x, _, _) => "yes"
  case _             => "no"
}

Scala specification says:

An infix operation pattern p;op;q is a shorthand for the constructor or extractor pattern op(p,q). The precedence and associativity of operators in patterns is the same as in expressions.

An infix operation pattern p;op;(q1,…,qn) is a shorthand for the constructor or extractor pattern op(p,q1,…,qn).