I know about couple of similar questions. They don't help me - code does not work if there is no existing key.
I need just some nice approach to append Map with value adding it to existing key (if it does exist) or putting as NEW key (if map does not contain appropriate key).
Following code works but I don't like it:
val a = collection.mutable.Map(("k1" -> 1), ("k2" -> 5))
val key = "k1"
val elem = a.get(key)
if (elem == None) {
a += ("k5" -> 200)
} else {
a.update(key, elem.get + 5)
}
Any point to better one? Current Scala version is 2.10.4 and I cannot currently switch to 2.11. Mutable map is not 100% limitation but preferred.
Here is, for example, similar question but I also need to account case of non-existing key which is not accounted there. At least we should understand a.get(key)
could be None
or add some better approach. Good idea was |+|
but I'd like to keep basic Scala 2.10.x.