I want to write a function like this:
def genericCase[T]() : PartialFunction[Any, T] = {
case Wrapper(_, item: T) => item
case Wrapper(item: T, _) => item
}
In words, I want a way to reuse the structure of a pattern match with different types.
The compiler tells me that due to type erasure, the case x: T
will never match. What is an alternative to do this kind of generic case statement? I also tried to use Types in the reflect API as an argument to the function, but we couldn't figure that out.
All you need is to add an implicit ClassTag
which allows to match on a generic class:
import scala.reflect.ClassTag
def genericCase[T: ClassTag]() : PartialFunction[Any, T] = {
case Wrapper(_, item: T) => item
case Wrapper(item: T, _) => item
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With