scala> 3 :: List(1,2)
res5: List[Int] = List(3, 1, 2)
scala> 3 +: List(1,2)
res6: List[Int] = List(3, 1, 2)
What's the difference between those two operators?
scala> 3 :: List(1,2)
res5: List[Int] = List(3, 1, 2)
scala> 3 +: List(1,2)
res6: List[Int] = List(3, 1, 2)
What's the difference between those two operators?
The difference is that +:
is an abstraction of ::
, which operates on generalized Seq
s rather than only List
s. For instance, +:
also works on Stream
s:
scala> 3 +: Stream(1,2)
res0: scala.collection.immutable.Stream[Int] = Stream(3, ?)
When you use it with a List
, it is functionally the same as ::
.
The methods +:
and ::
defined on the List
class have the following implementations,
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)
}
def ::[B >: A] (x: B): List[B] =
new scala.collection.immutable.::(x, this)
The method +:
needs to exist because it is inherited from SeqLike
. As pelotom says, this is the more general method.
However, I am not sure why the method List.::
needs to exist.
Update: The same question has already been asked. In the comments it is suggested that the method ::
exists for historical reasons.