问题
In immutable collection of SCALA a new object is created when length of collection changes Let us suppose I create a immutable Map and then perform concatenation. CODE=>
object Dcoder extends App
{
var map=Map("abc"-> 1,"xyz"->2)
var change =map++Map("change of object"+>3)
}
Now my Question is
a) Does the new object gets created because of ++ ??
b) Since I'm using a IMMUTABLE COLLECTION and length of Immutable collection has changed so new object is created ??
回答1:
From the documentation of ++
immutable.Map.++:
Adds a number of elements provided by a traversable object and returns a new collection with the added elements.
So indeed, it creates a new collection, remaining the old map
unmodified:
scala> var map = Map("abc" -> 1, "xyz" -> 2)
map: scala.collection.immutable.Map[String,Int] = Map(abc -> 1, xyz -> 2)
scala> var change = map ++ Map("change of object" -> 3)
change: scala.collection.immutable.Map[String,Int] = Map(abc -> 1, xyz -> 2, change of object -> 3)
scala> change
res9: scala.collection.immutable.Map[String,Int] = Map(abc -> 1, xyz -> 2, change of object -> 3)
scala> map
res10: scala.collection.immutable.Map[String,Int] = Map(abc -> 1, xyz -> 2)
You can use +=
to "modify" your map
likewise:
scala> map += "lol" -> 3
scala> map
res12: scala.collection.immutable.Map[String,Int] = Map(abc -> 1, xyz -> 2, lol -> 3)
Realize that I just put "modify", because this returns another map
(since it's immutable) object and assigns it to your map
variable.
回答2:
Yes to both questions. In fact, according to scala docs:
ms ++ kvs
creates map containing all mappings of ms as well as all key/value pairs of kvs.
More info here.
来源:https://stackoverflow.com/questions/50180300/immutablity-of-collection-map