0

Using the api documentation of Scala it is obvious how Lists are constructed using the :: Syntax, which refers to a method on Lists.

But the extractor in infix notation for pattern matching as in { case 1 :: 2 :: _ => ??? } would require an object with an unapply method. So my question is: Where does this undocumented extractor :: come from in Scala?

Mogsdad
  • 44,709
  • 21
  • 151
  • 275
Araeos
  • 171
  • 2
  • 9

2 Answers2

1

Here is how :: implementation looks like

/** A non empty list characterized by a head and a tail.
 *  @param head the first element of the list
 *  @param tl   the list containing the remaining elements of this list after the first one.
 *  @tparam B   the type of the list elements.
 *  @author  Martin Odersky
 *  @version 1.0, 15/07/2003
 *  @since   2.8
 */
@SerialVersionUID(509929039250432923L) // value computed by serialver for 2.11.2, annotation added in 2.11.4
final case class ::[B](override val head: B, private[scala] var tl: List[B]) extends List[B] {
  override def tail : List[B] = tl
  override def isEmpty: Boolean = false
}

For more info visit Scala's '::' operator, how does it work?

Nagarjuna Pamu
  • 14,737
  • 3
  • 22
  • 40
  • Thank you. This is correct and my assumption was not: This code is also [documented](https://www.scala-lang.org/files/archive/api/current/scala/collection/immutable/$colon$colon.html). I initially thought, every case class would have a corresponding object generated, but this is probably an implementation detail. – Araeos Dec 20 '17 at 09:55
  • Yes, There is extractor generated for `case class` by default. – Nagarjuna Pamu Dec 20 '17 at 09:58
0

In the case of :: on Lists, the extractor is generated as part of the case class ::. Usage of :: in pattern matching is referred to as constructor pattern.

Araeos
  • 171
  • 2
  • 9