我有一个mutable.Map
,我需要更改密钥(如果存在)。如果没有,我想添加一个新的映射。这是我的意思:
val m = mutable.HashMap[String, String]()
val default = "default"
val key = "key_to_change"
val newKey = "key_to_set"
if(m.contains(key)) {
val oldValue = m(key)
m remove key
m += newKey -> oldValue
} else m += newKey -> default
我想知道scala是否没有更简洁的方法来执行这种“密钥更改”。您能提出更好的解决方案吗?
答案 0 :(得分:3)
remove
"removes a key from this map, returning the value associated previously with that key as an option",所以
val value = m.remove(key).getOrElse(default)
m += newKey -> value