Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update a mutable hashmap element in Scala?

I wrote a function very similar to this:

def writeMyEl (x: TypeA, y: TypeB, z : TypeC) {
  if (myMutableHashMap.contains((x, y)))
    myMutableHashMap(x, y) = z else
      myMutableHashMap += (x, y) -> z
}

In real code Types A and B are enumerations and C is a case class. myMutableHashMap is defined as a val of type scala.collection.mutable.HashMap[(TypeA, TypeB), TypeC] inside the same class as the writeMyEl function.

The Scala (2.8) compiler says:

error: too many arguments for method update: (key: (TypeA, TypeB),value: TypeC)Unit

What am I doing wrong?

like image 995
Ivan Avatar asked Dec 21 '22 23:12

Ivan


1 Answers

Try myMutableHashMap((x, y)) = z. In fact, you don't need the check, since the documentation for += says "Adds a new key/value pair to this map. If the map already contains a mapping for the key, it will be overridden by the new value." So your function can just be written as

def writeMyEl (x: TypeA, y: TypeB, z : TypeC) {
  myMutableHashMap += (x, y) -> z
}
like image 52
Alexey Romanov Avatar answered Jan 07 '23 21:01

Alexey Romanov