5

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.

Sesquipedalian
  • 247
  • 1
  • 2
  • 9

1 Answers1

5

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
}
Petr
  • 62,528
  • 13
  • 153
  • 317