Reputation: 9521
I have a mutable.Map
which I need to change a key of if the key is present. If not I want to add a new mapping. Here is what I mean:
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
I wonder if scala does not have a more concise way to perform such "key-changing". Can you suggest a better solution?
Upvotes: 1
Views: 4493
Reputation: 170723
remove
"removes a key from this map, returning the value associated previously with that key as an option", so
val value = m.remove(key).getOrElse(default)
m += newKey -> value
Upvotes: 7