I am reading a scala book and they use two different type of cons operators when doing pattern matching on sequences and lists
+:
::
usually most functional languages use ::
as cons. I don't know why scala has 2 different type of operators for the cons.
I googled on the this as well ... but didn't find anything meaningful.
Thanks for the answer below. I understood from it that +:
is a generic operator and ::
is specific for lists. But my perhaps a follow up question is why would scala use two operators. why not just use one ::
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
}
and
override def +:[B >: A, That](elem: B)(implicit bf: CanBuildFrom[List[A], B, That]): That = bf match {
case _: List.GenericCanBuildFrom[_] => (elem :: this).asInstanceOf[That]
case _ => super.+:(elem)(bf)
}
that makes it clear - :: takes List and produces List, while +: is more generic form, that can build other collections - like Vector or ArrayBuffer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With