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

后端 未结 4 1517
再見小時候
再見小時候 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-04 05:41

    Let me summarise your problem:

    • You want to call a method on a immutable data structure
    • You want it to return some value and reassign a var
    • Because the data structure is immutable, you’ll need to
      • return a new immutable data structure, or
      • do the assignment inside the method, using a supplied closure

    So, either your signature has to look like

    def getOrElseUpdate(key: K): Tuple2[V, Map[K,V]]
    //... use it like
    val (v, m2) = getOrElseUpdate(k)
    map = m2
    

    or

    def getOrElseUpdate(key: K, setter: (Map[K,V]) => Unit): V
    //... use it like
    val v = getOrElseUpdate(k, map = _)
    

    If you can live with one of these solutions, you could add your own version with an implicit conversion but judging by the signatures alone, i wouldn’t think any of these is in the standard library.

提交回复
热议问题