4

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.

Community
  • 1
  • 1
dublintech
  • 16,815
  • 29
  • 84
  • 115

2 Answers2

9

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.

Daniel C. Sobral
  • 295,120
  • 86
  • 501
  • 681
6

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
Kyle
  • 21,978
  • 2
  • 60
  • 61