Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

idiomatic "get or else update" for immutable.Map?

What is the idiomatic way of a getOrElseUpdate for immutable.Map instances?. I use the snippet below, but it seems verbose and inefficient

var map = Map[Key, Value]()

def foo(key: Key) = {
  val value = map.getOrElse(key, new Value)
  map += key -> value
  value
}
like image 431
IttayD Avatar asked Dec 08 '10 09:12

IttayD


1 Answers

I would probably implement a getOrElseUpdated method like this:

def getOrElseUpdated[K, V](m: Map[K, V], key: K, op: => V): (Map[K, V], V) =
  m.get(key) match {
    case Some(value) => (m, value)
    case None => val newval = op; (m.updated(key, newval), newval)
  }

which either returns the original map if m has a mapping for key or another map with the mapping key -> op added. The definition of this method is similar to getOrElseUpdate of mutable.Map.

like image 191
Frank S. Thomas Avatar answered Nov 16 '22 00:11

Frank S. Thomas