Marek J
Marek J

Reputation: 1374

Lists in Scala - plus colon vs double colon (+: vs ::)

I am little bit confused about +: and :: operators that are available.

It looks like both of them gives the same results.

scala> List(1,2,3)
res0: List[Int] = List(1, 2, 3)

scala> 0 +: res0
res1: List[Int] = List(0, 1, 2, 3)

scala> 0 :: res0
res2: List[Int] = List(0, 1, 2, 3)

For my novice eye source code for both methods looks similar (plus-colon method has additional condition on generics with use of builder factories).

Which one of these methods should be used and when?

Upvotes: 40

Views: 15791

Answers (1)

Dima
Dima

Reputation: 40500

+: works with any kind of collection, while :: is specific implementation for List. If you look at the source for +: closely, you will notice that it actually calls :: when the expected return type is List. That is because :: is implemented more efficiently for the List case: it simply connects the new head to the existing list and returns the result, which is a constant-time operation, as opposed to linear copying the entire collection in the generic case of +:.

+: on the other hand, takes CanBuildFrom, so you can do fancy (albeit, not looking as nicely in this case) things like:

val foo: Array[String] = List("foo").+:("bar")(breakOut)

(It's pretty useless in this particular case, as you could start with the needed type to begin with, but the idea is you can prepend and element to a collection, and change its type in one "go", avoiding an additional copy).

Upvotes: 37

Related Questions