Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does :+= method do defined for scala.collection.immutable.Vector?

Tags:

scala

given the following scala code:

var v1 = Vector("foo")
v1 :+= ""

What does :+= do, how is it different from += and where is it defined?

Thanks!

PS: Yes, i did search on this, but didn't found anything. Found trough this (http://simply.liftweb.net/index-2.3.html#prev) tutorial.

like image 491
the dude Avatar asked Feb 22 '13 21:02

the dude


1 Answers

Scala sequences have three operators that produce new sequences by adding something to an old sequence: ++, +: and :+. The ++ operator simply concatenates a Scala sequence with another (or a traversable). The other two prepend and append elements, respectively.

The peculiar syntax of +: and :+ is due to the way they are used. Any operator ending with : applies to the object on the right, not on the left. That is:

1 +: Seq.empty == Seq.empty.+:(1)

By symmetry, the other operator is :+, though the colon is meaningless in that case. This let you write things like this:

scala> 1 +: 2 +: 3 +: Seq.empty :+ 4 :+ 5 :+ 6
res2: Seq[Int] = List(1, 2, 3, 4, 5, 6)

Note how the elements being added end up in the exact same position as they appear in the expression. This makes it easier to visualize what's happening.

Now, you have :+=, not any of the above. As it happens, Scala allows one to concatenate any operator with = to make up a get-and-set operation. So the common increment expression:

x += 1

Actually means

x = x + 1

Likewise,

v1 :+= ""

means

v1 = v1 :+ ""

which creates a new vector by appending the empty string to the old vector, and then assigns it to v1.

like image 92
Daniel C. Sobral Avatar answered Oct 03 '22 08:10

Daniel C. Sobral