You can even write:
val head :: tail = List(1, 2, 3)
Basically anything where a pattern is expected (an assignment, a match
statement or a line in a for-comprehension) can take an extractor, which is defined as an entity with an unapply
method.
One of the pieces of syntactic sugar that scala provides you with is that; if you have an extractor X(a, b)
, this can be written as a X b
. Here's an example with case classes (which have a default extractor):
scala> case class X(a: Int, b: String)
defined class X
scala> val a X b = X(1, "two")
a: Int = 1
b: String = two
The ability to write such entities infix extends to types as well:
scala> type MappedTo[A, B] = Map[A, B]
defined type alias MappedTo
scala> def foo(m: Int MappedTo String) = m foreach println
foo: (m: MappedTo[Int,String])Unit
Note that in neither case, does scala restrict such infix operators to symbolic identifiers