Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Idiomatic Scala Map upsert

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!

like image 504
Dave Ray Avatar asked Jan 03 '09 04:01

Dave Ray


1 Answers

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

like image 164
sblundy Avatar answered Oct 14 '22 19:10

sblundy