Difference between: and ++ for list concatenation

Possible duplicate:
Scala list concatenation: vs ++

In Scala, let's 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 combine the 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.

+4
source share
2 answers

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

The difference arises from two things. Firstly, List is one of the original Scala collections, it is used a lot in the compiler and undergoes special optimization. The concatenation :: is the same as in the ML language family, one of the great Scala inspirations and ::: extrapolated from it.

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

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

+9
source

From the docs:

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

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

You can see that ++ works for any Iterable , and ::: specifically for List

 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 
+6
source

All Articles