Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala difference between "+:" and "::"

Tags:

scala

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 ::

like image 500
Knows Not Much Avatar asked Dec 15 '22 14:12

Knows Not Much


1 Answers

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.

like image 165
jdevelop Avatar answered Jan 05 '23 21:01

jdevelop