what is equivalent function of Map.compute in scala.collection.mutable.Map

you can use update and getOrElse as in

val x= scala.collection.mutable.Map("a"->1,"b"->2)
x.update("c",x.getOrElse("c",1)+41)
x.update("a",x.getOrElse("a",1)+41)

There is getOrElseUpdate defined in mutable.MapLike trait which does exactly what you want:

def getOrElseUpdate(key: K, op: ⇒ V): V

If given key is already in this map, returns associated value. Otherwise, computes value from given expression op, stores with key in map and returns that value.


The correct answer above can be simplified by configuring default value for the case when the key is absent. Also, read then update value can be done by one operator map("key") += value

val map = collection.mutable.Map("a" -> 1, "b" -> 2).withDefaultValue(1)
map("c") += 41
map("a") += 41

println(map)

returns Map(b -> 2, a -> 42, c -> 42)