如何在 Scala 中更新可变的 hashmap 元素?
我写了一个与此非常相似的函数:
def writeMyEl (x: TypeA, y: TypeB, z : TypeC) {
if (myMutableHashMap.contains((x, y)))
myMutableHashMap(x, y) = z else
myMutableHashMap += (x, y) -> z
}
在实际代码中,类型 A 和 B 是枚举,C 是案例类。 myMutableHashMap 被定义为与 writeMyEl 位于同一类中的 scala.collection.mutable.HashMap[(TypeA, TypeB), TypeC] 类型的 val
代码>函数。
Scala (2.8) 编译器说:
error: too many arguments for method update: (key: (TypeA, TypeB),value: TypeC)Unit
我做错了什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尝试 myMutableHashMap((x, y)) = z。事实上,您不需要检查,因为
+=
的文档说“向此映射添加一个新的键/值对。如果映射已经包含该键的映射,它将被新值覆盖。”所以你的函数可以写成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