title: Using collection.Map in foldleft
body: <p>Can you use collection.Map as the accumulator/return value of a fold?</p>
  
  <p>For example:</p>
  
  <pre><code>Seq(1, 2, 3).foldLeft(collection.Map.empty[Int, Int]) { 
    case (map, i) =&gt; map.asInstanceOf[collection.Map[Int, Int]] + (i -&gt; i)
  }
  </code></pre>
  
  <p>Scala gives me the following type error:</p>
  
  <pre><code> found   : scala.collection.Map[Int,Int]
   required: scala.collection.immutable.Map[Int,Int]
                Seq(1, 2, 3).foldLeft(collection.Map.empty[Int, Int]) { case (map, i) =&gt; map.asInstanceOf[collection.Map[Int, Int]] + (i -&gt; i) }
  </code></pre>
  
  <p>Why is it enforcing use of <code>collection.immutable.Map</code> instead of <code>collection.Map</code>?</p>
  
  <p>EDIT: The pointless casting is a bit misleading so I want to make my intent more clear. I am specifically using <code>collection.Map</code> inside of the fold because it is the superclass of <code>immutable.Map</code> and <code>mutable.Map</code>. In reality, I am using a function inside of the fold that returns <code>collection.Map</code>, consider:</p>
  
  <pre><code>scala&gt; def func(map: collection.Map[Int, Int]): collection.Map[Int, Int] = map
  func: (map: scala.collection.Map[Int,Int])scala.collection.Map[Int,Int]
  
  scala&gt; Seq(1, 2, 3).foldLeft(collection.Map.empty[Int, Int])((map, i) =&gt; map + (i -&gt; i))
  res11: scala.collection.immutable.Map[Int,Int] = Map(1 -&gt; 1, 2 -&gt; 2, 3 -&gt; 3)
  
  scala&gt; Seq(1, 2, 3).foldLeft(collection.Map.empty[Int, Int])((map, i) =&gt; func(map) + (i -&gt; i))
  &lt;console&gt;:9: error: type mismatch;
   found   : scala.collection.Map[Int,Int]
   required: scala.collection.immutable.Map[Int,Int]
                Seq(1, 2, 3).foldLeft(collection.Map.empty[Int, Int])((map, i) =&gt; func(map) + (i -&gt; i))
                                                                                            ^
  </code></pre>
  
  <p>An answer given below does work: changing the start value from <code>collection.Map.empty[Int, Int]</code> to <code>collection.Map[Int, Int]()</code>. I'm not sure why this makes a difference though:</p>
  
  <pre><code>scala&gt; Seq(1, 2, 3).foldLeft(collection.Map[Int, Int]())((map, i) =&gt; func(map) + (i -&gt; i))
  res13: scala.collection.Map[Int,Int] = Map(1 -&gt; 1, 2 -&gt; 2, 3 -&gt; 3)
  </code></pre>