score:11

Accepted answer

You're probably using immutable.Map. You need to use mutable.Map, or replace the set instead of modifying it with another immutable map.

Here's a reference of a description of the mutable vs immutable data structures.

So...

import scala.collection.mutable.Map
var m = Map[Int,Set[Int]]()
m += 1 -> Set(1)
m(1) += 2

score:4

In addition to @Stefan answer: instead of using mutable Map, you can use mutable Set

import scala.collection.mutable.{Set => mSet}
var m = Map[Int,mSet[Int]]()
m += 1 -> mSet(1)
m(1)+=2

mSet is a shortcut to mutable Set introduced to reduce verbosity.

scala> m
res9: scala.collection.immutable.Map[Int,scala.collection.mutable.Set[Int]] = Map(1 -> Set(2, 1))

score:4

I think what you really want here is a MultiMap

import collection.mutable.{Set, Map, HashMap, MultiMap}
val m = new HashMap[Int,Set[Int]] with MultiMap[Int, Int]
m.addBinding(1,1)
m.addBinding(1,2)
m.addBinding(2,3)

Note that m itself is a val, as it's the map itself which is now mutable, not the reference to the map

At this point, m will now be a:

Map(
  1 -> Set(1,2),
  2 -> Set(3)
)

Unfortunately, there's no immutable equivalent to MultiMap, and you have to specify the concrete subclass of mutable.Map that you'll use at construction time.

For all subsequent operations, it's enough to just pass the thing around typed as a MultiMap[Int,Int]


Related Query

More Query from same tag