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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With