Scala List method `::` vs `+:`

149 Views Asked by At

Can't see the real difference between :: and +: method of Scala List.

I used REPL to test and can't see diff from the result.

Anyone can give me how can I use that properly?

1

There are 1 best solutions below

1
On BEST ANSWER

Looking at the code of List, +: uses :: (cons) operator for prepending.

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)
}

In general, +: is defined in SeqLike and any collection implementing SeqLike can use the same.

On the other hand :: is defined in List and can only be used by List.