title: Scala: filter and cast in one operation
body: <p>Given a heterogeneous sequence, how can I pull out only members of a certain type, and operate on those members in a type-safe way?</p>
  
  <p>If I have: 
  </p>
  
  <pre><code>trait Foo
  case class Bar(baz: String)
  case class Qux(bar: Bar, quux: String) extends Foo
  case class Corge(grault: Int) extends Foo
  </code></pre>
  
  <p>If I want to take this sequence of mixed <code>Corges</code> and <code>Quxes</code>...</p>
  
  <pre class="lang-scala prettyprint-override"><code>val s = Seq[Foo](Corge(1), Qux(Bar("2"), "3"), Qux(Bar("4"), "5"), Corge(6), Qux(Bar("2"), "7"))
  </code></pre>
  
  <p>...and pull out just the <code>Quxes</code>, grouped by <code>Bar</code>:</p>
  
  <pre class="lang-scala prettyprint-override"><code>Map(
    Bar(2) -&gt; List(Qux(Bar(2),3), Qux(Bar(2),7)), 
    Bar(4) -&gt; List(Qux(Bar(4),5))
  )
  </code></pre>
  
  <p>I can do this:</p>
  
  <pre class="lang-scala prettyprint-override"><code>s filter { f =&gt; f.isInstanceOf[Qux] } groupBy { 
      f =&gt; f.asInstanceOf[Qux].bar }
  </code></pre>
  
  <p>Or I can do this:</p>
  
  <pre class="lang-scala prettyprint-override"><code>(s.filter({ f =&gt; f.isInstanceOf[Qux] }).asInstanceOf[Seq[Qux]]) groupBy { 
      q =&gt; q.bar }
  </code></pre>
  
  <p>But either way I need two <code>instanceOf</code> checks, when it seems like I should be able to get away with one. Or none. Is there some clever pattern-matching solution I'm missing?</p>