tl;dr It isn't pattern matching the operator, it's pattern matching a case class called ::
There are a couple of things happening at the same time. First of all, there may be a bit of confusion, because ::
is a method on List:
val x: List[Int] = 1 :: 2 :: 3 :: Nil
But there is also a case class ::
that, according to the docs is:
A non empty list characterized by a head and a tail.
More info here
Scala's case classes automatically come with extractor methods(unapply
), which allow pattern matching, as in case User(name, age) => ...
.
You are also allowed to use the case class name in an infix position (although you shouldn't do so, except when the case class is used like an operator, such as in this case). So case head :: tail => ...
is the same as case ::(head, tail) => ...
. More info here
When pattern matching, you can use _
to mean that there will be a value there, but you don't care about it, so you aren't providing it a name.
So the three cases you provided are roughly:
- A tuple where the first value is 0, and the second value is a list with a head to be called
h
, and a tail which we will ignore.
- A tuple with some integer to be called
k
, and a list with a head that we don't care about, and a tail, which we will call tail
. Also, k
must be greater than 0
- Anything else, then throw a NoSuchElementException