In following code I want the hitA
to be called only when the type of i
is A
. The type to check is provided as a type parameters, therefore it is type erased and a match
fails on it, giving me a compiler warning:
abstract type pattern T is unchecked since it is eliminated by erasure
The desired output of the code is:
Hit A
Not hit
In current version when I run the code I get Hit A followed by a ClassCastException
.
I understand what is happening and why the warning and the exception is there, but I am not sure how to get around this. I have read basic articles on TypeTags and I understand how to use them in basic cases, but I fail to see how could I create a partial function using TypeTags.
import scala.reflect.runtime.universe._
object TestMatch extends App {
abstract class I
class A extends I {
def hitA() = println("Hit A")
}
class B extends I
def processOpGen[T <: I : TypeTag](op: PartialFunction[I, Unit])(i: I) = {
val fallback : PartialFunction[I, Unit] = {case _ => println("Not hit")}
(op orElse fallback)(i)
}
def partialMatchGen[T <: I : TypeTag](op: T => Unit)(i: I) = {
processOpGen[T] {
case c: T => op(c) // can TypeTag be used here for matching somehow?
}(i)
}
partialMatchGen[A](a => a.hitA())(new A)
partialMatchGen[A](a => a.hitA())(new B)
}