30

I'm working with a map in Scala and doing the usual "if there's no value associated with a key, create it, put it in the map and return it":

def alphaMemory(key : AlphaMemoryKey) = {
    var am = map.getOrElse(key, null)
    if(am == null) {
        am = new AlphaMemory(key)
        map.put(key, am)
    }
    am
}

To me, this does not feel like idiomatic Scala code. It feels like Java. Is there a more succinct way of writing this? It looked like maybe I could override Map.default() to insert the new value and return it. Not sure though.

Thanks!

om-nom-nom
  • 62,329
  • 13
  • 183
  • 228
Dave Ray
  • 39,616
  • 7
  • 83
  • 82

1 Answers1

40

mutable.Map has getOrElseUpdate which does exactly what you want, no idiom necessary.

Hosam Aly
  • 41,555
  • 36
  • 141
  • 182
sblundy
  • 60,628
  • 22
  • 121
  • 123