title: Filling mutable map with defaults OR alternative to mutable map for Scala function memoization
body: <p>I know that <code>withDefault</code> allows you to specify a function that will be applied to a key to produce a default map value, but that function gets called every time you pass an unknown key into the map, even if you pass in the same key -- the values aren't stored in the map.</p>
  
  <pre><code>scala&gt; case class Foo(foo: String) {}
  defined class Foo
  
  scala&gt; val m = mutable.OpenHashMap[String, Foo]().withDefault( s =&gt; {
         | println(s"creating new value for $s")
         | Foo(s)
         | })
  m: scala.collection.mutable.Map[String,Foo] = Map()
  
  scala&gt; m("elvis")
  creating value for elvis
  res1: Foo = Foo(elvis)
  
  scala&gt; m("elvis")
  creating value for elvis
  res2: Foo = Foo(elvis)
  </code></pre>
  
  <p>Now obviously this isn't a big deal for case classes, but if the values are themselves mutable collections, or any other mutable object, it's not very helpful. I'm reduced to using <code>getOrElseUpdate</code> wherever I access the map. Surely there's a more elegant solution?</p>
  
  <p>Or, since in this case the 'default' function is actually the <em>only</em> way I'm going to be generating map values, is there an elegant, Scala-like solution for caching function return values that doesn't involve mutable maps?</p>
  
  <hr>
  
  <p><strong>ETA:</strong> To be clear, I do want to call the function again for each <em>different</em> key. But for a given key, I want to only call the function once, and get the same object back the next time.</p>