title: How does foo(a)(b) += x work in Scala?
body: <p>I have been counting occurences with a mutable map:</p>
  
  <pre><code>var bar = collection.mutable.Map[Int, Int]().withDefaultValue(0)
  </code></pre>
  
  <p>Now <code>bar(a) += b</code> works just fine, no matter if the key <code>a</code> is present in <code>bar</code> already or not (in which case it will then be added).</p>
  
  <p>I tried the same thing with a mutable map of mutable maps:</p>
  
  <pre><code>var foo = collection.mutable.Map[Int, collection.mutable.Map[Int, Int]]().
            withDefaultValue(collection.mutable.Map().withDefaultValue(0))
  </code></pre>
  
  <p>How does <code>foo(a)(b) += x</code> look without syntactic sugar?</p>
  
  <p>Using <a href="https://stackoverflow.com/questions/2662984/what-are-all-the-instances-of-syntactic-sugar-in-scala">What are all the instances of syntactic sugar in Scala?</a> I would assume it expands to:</p>
  
  <pre><code>foo.apply(a).put(b, foo.apply(a).apply(b) + x)
  </code></pre>
  
  <p>But why does this not update <code>foo</code> itself accordingly like in the introductory example (i.e. <code>foo</code> will not have a dedicated value for key <code>a</code> if it wasn't present before)?</p>
  
  <p><strong>Edit:</strong> As <a href="https://stackoverflow.com/questions/19260564/how-does-fooab-x-work-in-scala#comment28548572_19260729">Perseids pointed out</a>, <code>foo(a)(b) += x</code> will change the mutable default value. Is this a desired feature?
  Using <code>getOrElseUpdate</code> as suggested by <a href="https://stackoverflow.com/a/19260729/2860570">DaoWen</a> seems to be the best way to overcome both problems. But while that works well for functions of type <code>Int =&gt; Int =&gt; Int</code> it becomes really cumbersome for functions of type <code>Int =&gt; Int =&gt; Int =&gt; Int =&gt; Int</code>. So I'm still happy for any suggestions!</p>