Scala – List patterns

List(…) is an instance of a library-defined extractor pattern.

The “cons” pattern x :: xs is a special case of an infix operation pattern. You know already that, when seen as an expression, an infix operation is equivalent to a method call.

 

When seen as a pattern, an infix operation such as p op q is equivalent to op(p, q). That is, the infix operator op is treated as a constructor pattern. In particular, a cons pattern such as x :: xs is treated as ::(x, xs).

There is a class named :: that corresponds to the pattern constructor. It is named scala.:: and is exactly the class that builds nonempty lists.

So :: exists twice in Scala, once as a name of a class in package scala, and again as a method in class List. The effect of the method :: is to produce an instance of the class scala.::.

Leave a comment