Search code examples
arraysscalacollectionsassignment-operator

Why is the ++: operator in the Scala language so strange?


I am using the ++: operator to get a collection of two collections, but the results I get using these two methods are inconsistent:

scala> var r = Array(1, 2)
r: Array[Int] = Array(1, 2)
scala> r ++:= Array(3)
scala> r
res28: Array[Int] = Array(3, 1, 2)

scala> Array(1, 2) ++: Array(3)
res29: Array[Int] = Array(1, 2, 3)

Why do the ++: and ++:= operators give different results? This kind of difference does not appear with the ++ operator.

The version of Scala I am using is 2.11.8.


Solution

  • Since it ends in a colon, ++: is right-associative. This means that Array(1, 2) ++: Array(3) is equivalent to Array(3).++:(Array(1, 2)). ++: can be thought of as "prepend the elements of the left array to the right array."

    Since it's right-associative, r ++:= Array(3) desugars to r = Array(3) ++: r. This makes sense when you consider that the purpose of ++: is prepending. This desugaring holds true for any operator that ends in a colon.

    If you want to append, you can use ++ (and ++=).