title: Using collect on maps in Scala
body: <p>I recently stumbled over this <a href="http://daily-scala.blogspot.com/2010/04/filter-with-flatmap-or-collect.html" rel="noreferrer">post</a>, which "introduces" the <code>collect</code> method for Scala collections. The usage is straight forward:</p>
  
  <pre><code>scala&gt; val ints = List(1, "2", 3) collect { case i: Int =&gt; i }
  ints: List[Int] = List(1, 3)
  </code></pre>
  
  <p>Now <strong>maps</strong> are basically lists of key-value pairs, which are represented by tuples in Scala. So you might wanna try something like this:</p>
  
  <pre><code>scala&gt; val pairs = Map(1 -&gt; "I", "II" -&gt; 2)
  pairs: scala.collection.immutable.Map[Any,Any] = Map(1 -&gt; I, II -&gt; 2)
  
  scala&gt; val intsToStrings = pairs collect { case pair: (Int, String) =&gt; pair }
  </code></pre>
  
  <p>The compiler complains of course due to the type erasure model of the JVM, so the first thing we try is using existential types:</p>
  
  <pre><code>scala&gt; val intsToStrings = pairs collect { case pair: (_, _) =&gt; pair }
  intsToString: scala.collection.immutable.Map[Any,Any] = Map(1 -&gt; I, II -&gt; 2)
  </code></pre>
  
  <p>Although the code passed the compiler, and the result is "correct" (we wanted pairs => we got pairs) we still didn't get what we actually wanted. The second attempt looks like this:</p>
  
  <pre><code>scala&gt; val intsToStrings = pairs collect {
       |    case pair: (_, _) if pair._1.isInstanceOf[Int] &amp;&amp; pair._2.isInstanceOf[String] =&gt; pair
       | }
  intsToStrings: scala.collection.immutable.Map[Any,Any] = Map(1 -&gt; I)
  </code></pre>
  
  <p>Ok, we are almost there:</p>
  
  <pre><code>scala&gt; val realIntsToRealStrings = intsToStrings map {
       |    pair =&gt; (pair._1.asInstanceOf[Int], pair._2.asInstanceOf[String])
       | }
  realIntsToRealStrings: scala.collection.immutable.Map[Int,String] = Map(1 -&gt; I)
  </code></pre>
  
  <p>We did it, but instead of only casting from <code>(Any,Any)</code> to <code>(Int,String)</code> we actually copied each pair and thus created a new pair.</p>
  
  <p>Now comes the question part. As I mentioned "The compiler complains of course..." I made it sound like I really know what I'm talking about. I don't! All I know is that Java didn't have generics from the beginning. At some point generics came into Java but not into the JVM. So the compiler checks all the types, but as soon as the code is running, JVM does not care for the parametric type. It only sees that it's a <code>Map</code> or a <code>List</code> but not that it's a <code>Map[String, Int]</code> or <code>List[Int]</code>.</p>
  
  <p>So here is my question.</p>
  
  <p>With all the checking, casting and mapping, we managed to transfer a <code>Map[Any,Any]</code> to <code>Map[String,Int]</code>. Is there a better way of doing that? I mean the types are there, JVM just does not see them (as far as I am concerned)...</p>