I’m trying to build a mutable map from integers to a mutable set of integers in Scala.
For example, I would like to have the mappings of the form 1 -> (2,3) and be able to update
them later using the key value. The code that I use is as follows:
import scala.collection.mutable._
val map = Map[Int, Set[Int]]()
map: scala.collection.mutable.Map[Int,scala.collection.mutable.Set[Int]] = Map()
map += (1 -> Set(2,3))
res15: map.type = Map(1 -> Set(2, 3))
So far good, but when I try to do something like
map.get(1) += 4
I get an assignment to val error. What is confusing to me is that map.get() should return a
Set of type scala.collection.mutable.Set which can be updated. Can someone please shed some
light what’s going on here?
The issue in this case is that
get()returns an option (Option[scala.collection.mutable.Set[Int]]), which you need to “unpack”:The reason Map’s
get()function returns an option is that there might not be a value for any given key, and Scala does not like throwing exceptions like its Java API counterpart.Alternatively you could use the
apply()method, which directly returns the requested value and throws an exception in case of failure:I haven’t quite figured out why you’d get a “reassignment to val” error with the code you’ve tried, though. In my case (Scala 2.10), it says the following:
Which version of Scala are you using?