Reputation: 61
object Dcoder extends App {
var c = scala.collection.immutable.Map(12 -> "jd", 13 -> "ff")
c = c ++ Map(16 -> "hh", 17 -> "℅")
println(c)
c ++= Map(18 -> "|||")
println(c)
}
a = a ++ Map()
as well as a ++= Map()
performs concatenation. Does a=a++b
and a++=b
mean the same?
Upvotes: 0
Views: 2136
Reputation: 44918
Sometimes they are the same, sometimes they are not.
If the collection is immutable (e.g. List
), then it has no special method called ++=
, so the statement
collection ++= someOtherCollection
is syntactic sugar, and it is desugared into
collection = collection ++ someOtherCollection
On the other hand, most mutable collections (e.g. ListBuffer
) have a special ++=
method, so that
collection ++= someOtherCollection
mutates collection
in-place by adding all elements someOtherCollection
.
To see that ++=
and = ... ++
really behave differently, consider the following two examples:
var x = collection.mutable.ListBuffer(1, 2, 3)
val y = collection.mutable.ListBuffer(4, 5)
val z = x
x ++= y
println(x)
println(z)
This prints
ListBuffer(1, 2, 3, 4, 5)
ListBuffer(1, 2, 3, 4, 5)
But
var x = collection.mutable.ListBuffer(1, 2, 3)
val y = collection.mutable.ListBuffer(4, 5)
val z = x
x = x ++ y
println(x)
println(z)
prints
ListBuffer(1, 2, 3, 4, 5)
ListBuffer(1, 2, 3)
because ++
forces the creation of a completely new collection, that is not referenced by z
.
Upvotes: 4
Reputation: 1954
Its the same as a = a+2
and a+=2
in case of Integer
For second question, a=a++b
and a++=b
depends on the type of a and b. Depends if they support ++ and ++= operator or not
Upvotes: 0