开发者

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 enu开发者_JAVA百科merations 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?


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
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜