Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between ::: and ++ for concatenating Lists [duplicate]

Tags:

scala

Possible Duplicate:
Scala list concatenation, ::: vs ++

In Scala, say I have two lists

scala> val oneTwo = List(1,2)
oneTwo: List[Int] = List(1, 2)

and

scala> val threeFour = List(3,4)
threeFour: List[Int] = List(3, 4)

I can concatenates Lists by doing:

scala> oneTwo ::: threeFour
res30: List[Int] = List(1, 2, 3, 4)

Or

scala> oneTwo ++ threeFour
res31: List[Int] = List(1, 2, 3, 4)

What is the difference between both approaches?

Thanks.

like image 980
dublintech Avatar asked Dec 07 '22 09:12

dublintech


2 Answers

The ::: method is specific to List, while ++ is part of any Traversable.

The difference arise out of two things. First, List is one of the original Scala collections, used a lot in the compiler, and subject to special optimizations. The :: concatenation is the same as used in the ML family of languages, one of the big Scala inspirations, and ::: extrapolates from it.

On the other hand, ++ came along with the redesign of Scala collections on Scala 2.8.0, which made methods and inheritance uniform. I think it existed before that (on Set, for example), but the collections did not share a common superclass, so it was basically an ad hoc method for other collections.

In terms of performance, ::: should beat ++, but probably not significantly.

like image 110
Daniel C. Sobral Avatar answered Jan 16 '23 10:01

Daniel C. Sobral


From the docs:

::: [B >: A](prefix : List[B]) : List[B]

++ [B >: A](that : Iterable[B]) : List[B]

You can see the ++ works for any Iterable while ::: is specifically for List's

scala> val oneTwo = List(1,2)
oneTwo: List[Int] = List(1, 2)

scala> val threeFour = List(3,4)
threeFour: List[Int] = List(3, 4)

scala> val fiveSix = Array(5,6)
fiveSix: Array[Int] = Array(5, 6)

scala> oneTwo ++ fiveSix
res2: List[Int] = List(1, 2, 5, 6)

scala> oneTwo ::: fiveSix
<console>:10: error: value ::: is not a member of Array[Int]
              oneTwo ::: fiveSix
like image 34
Kyle Avatar answered Jan 16 '23 10:01

Kyle