Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I write a function that performs a case statement with a generic type? [duplicate]

Tags:

scala

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.

like image 603
Sesquipedalian Avatar asked Jul 17 '13 15:07

Sesquipedalian


1 Answers

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
}
like image 123
Petr Avatar answered Oct 23 '22 23:10

Petr