Scala sequences have three statements that produce new sequences, adding something to the old sequence: ++ , +: and :+ . The ++ operator simply combines the Scala sequence with another (or passing) one. The remaining two adds and adds elements, respectively.
The peculiar syntax of +: and :+ is determined by how they are used. Any statement ending in : applies to the object on the right, and not on the left. I.e:
1 +: Seq.empty == Seq.empty.+:(1)
By symmetry, another operator is :+ , although the colon in this case is pointless. This will allow you to write things like this:
scala> 1 +: 2 +: 3 +: Seq.empty :+ 4 :+ 5 :+ 6 res2: Seq[Int] = List(1, 2, 3, 4, 5, 6)
Notice how the elements you add are in the same position as in the expression. This facilitates the visualization of what is happening.
Now you have :+= , and not all of the above. As it happens, Scala allows you to combine any operator with = to create a get-and-set operation. Thus, the general expression of the increment:
x += 1
Actually mean
x = x + 1
Similarly
v1 :+= ""
means
v1 = v1 :+ ""
which creates a new vector by adding an empty string to the old vector and then assigns it to v1 .
source share