Reputation: 26048
I have an immutable HashMap and want to add/remove values from it. The Scala api docs say that I have to use +=
and -=
methods, but they don't work and I get the following error:
error: value += is not a member of scala.collection.immutable.HashMap
How do I add or remove values from a HashMap in Scala?
Upvotes: 4
Views: 12618
Reputation: 21567
You are watching api for mutable
HashMap, to add pair to immutable HashMap use +
hashMap + ("key", "value")
or if you want to remove use -
hashMap - "key"
But you should remember that it would create a new structure
As for +=
method, i think that this design is not good, because in such case you have to use var
instead of val
, and that's not a functional way
Upvotes: 5
Reputation: 38045
There is no method +=
in immutable collections, but compiler rewrites constructions like a <opname>= b
to a = a <opname> b
if there is no method <opname>=
in a
.
var myMap = Map[Int, String]()
myMap += (1, "a")
Last line actually means:
myMap = myMap + (1, "a")
Upvotes: 3
Reputation: 62855
It does not work because immutable map yields new instance instead of modifying existing one (thus it is immutable). So using val with immutable map is not a legal:
scala> val foo = Map.empty[Int, Int]
foo: scala.collection.immutable.Map[Int,Int] = Map()
scala> foo += 1 -> 2
<console>:9: error: value += is not a member of scala.collection.immutable.Map[Int,Int]
foo += 1 -> 2
^
scala> var bar = Map.empty[Int, Int]
bar: scala.collection.immutable.Map[Int,Int] = Map()
scala> bar += 2 -> 2
scala> bar
res2: scala.collection.immutable.Map[Int,Int] = Map(2 -> 2)
If you against using vars, opt to mutable maps.
Upvotes: 1