Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala unapplySeq extractor syntax

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

like image 651
Brian Kent Avatar asked Jun 22 '15 15:06

Brian Kent


1 Answers

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).

like image 162
bjfletcher Avatar answered Nov 20 '22 17:11

bjfletcher