Monday, August 27, 2012

Map#getOrElseUpdate

When manipulating data in a map, I often have to use this idiom, in java

Map map = new Map<>();
Value v = map.get(key);
if(v == null) {
  v = new DefaultValue();
  map.put(key, v)

}
// do something with v

In scala, I found this really nice function on the mutable.Map: getOrElseUpdate. The implementation is located on the MapLike trait and is pretty straightforward:

/** 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.
   *  @param  key the key to test
   *  @param  op  the computation yielding the value to associate with `key`, if
   *              `key` is previously unbound.
   *  @return     the value associated with key (either previously or as a result
   *              of executing the method).
   */
  def getOrElseUpdate(key: A, op: => B): B =
    get(key) match {
      case Some(v) => v
      case None => val d = op; this(key) = d; d
    }

With this function, the previous code just become:

Value v = map.getOrElseUpdate(key, new DefaultValue())

No comments:

Post a Comment