title: ClassCastException in a higher order generic function
body: <p>I have a code that tries to wrap a function in another that does dynamic type checking:  </p>
  
  <pre><code>class Base
  
  class Foo extends Base
  
  class Bar extends Base
  
  object Main{
    def checker[A &lt;: Base]( func : A =&gt; String) : Base =&gt; String =
      (b : Base) =&gt; b match {
        case a : A =&gt; func(a)
        case _ =&gt; "error"
      }
  
    def fooFunc(f : Foo) = "It's a foo"
  
    def main(arg : Array[String]) {
      val check = checker(fooFunc)
  
      println(check(new Foo) + ", " + check(new Bar))
    }
  }
  </code></pre>
  
  <p>This produces the following error:</p>
  
  <pre><code>Exception in thread "main" java.lang.ClassCastException: Bar cannot be cast to Foo
      at Main$$anonfun$1.apply(Main.scala:17)
      at Main$.main(Main.scala:19)
      at Main.main(Main.scala)
  </code></pre>
  
  <p>If I remove the type parameter and replace A with Foo in the definition of checker, it works well. However, if I keep the type parameter but omit the function argument and replace func(a) with "good", I get "good" for both Foo and Bar.</p>
  
  <p>Is this what is called type erasure? I'm not well familiar with the concept..<br>
  Also, I'd love to hear a solution around this.</p>