xuejianbest
xuejianbest

Reputation: 323

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.

Upvotes: 4

Views: 322

Answers (2)

prasanna kumar
prasanna kumar

Reputation: 293

Here colon(:) means that the function has right associativity

so, for instance coll1 ++: coll2 is similar to (coll2).++:(coll1)

Which generally means the elements of the left collection is prepended to right collection

Case-1:

Array(1,2) ++: Array(3)
Array(3).++:Array(1,2) 
Elements of the left array is prepended to the right array 
so the result would be Array(3,1,2)

Case-2:

 r = Array(1,2)
 r ++:= Array(3) //This could also be written as the line of code below
 r = Array(3) ++: r
   = r. ++: Array(3)
   = Array(1,2). ++: Array(3) //Elements of the left array is prepended to the right array 
 so their result would be Array(1,2,3)

Hope this solves the query Thank you :)

Upvotes: 0

Brian McCutchon
Brian McCutchon

Reputation: 8584

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 ++=).

Upvotes: 6

Related Questions