4

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?

3 Answers 3

5

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

Sign up to request clarification or add additional context in comments.

6 Comments

- or + put alone will not modify hashMap
@om-nom-nom it will return a new map
how do I add many keys-values for one time? Like hashMap + ("key", "value") + ("key2", "value2")
by the way, there should be hashMap + ("key" -> "value")
@MariusKavansky hashMap ++ Seq("foo" -> "bar", "bar" -> "baz")
|
3

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")

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.