idiomatic “get or else update” for immutable.Map?

后端 未结 4 1519
再見小時候
再見小時候 2021-02-04 05:01

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, Val         


        
4条回答
  •  无人及你
    2021-02-04 05:51

    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.

提交回复
热议问题