Reputation: 12436
Lets say I want to write generic function foo
that will use pattern matching to check whether passed argument is of type of it's generic argument T
Naive attempt:
def foo[T]: PartialFunction[Any, Boolean] = {
case x: T =>
true
case _ =>
false
}
... won't work since T
gets ereased. Compiller warning confirms that:
Warning:(11, 13) abstract type pattern T is unchecked since it is eliminated by erasure
case x: T =>
^
What is the best way to get it work?
Upvotes: 2
Views: 166
Reputation: 5426
Scala has introduced ClassTag
s for this purpose. They can be obtained by an implicit parameter, and will be automatically provided, which means you don't have to worry about the parameter when calling the method:
import scala.reflect.ClassTag
def foo[T](implicit tag: ClassTag[T]): PartialFunction[Any, Boolean] = {
case x: T =>
true
case _ =>
false
}
val isString = foo[String] // ClassTag gets provided implicitly here
isString("Hallo") // will return true
isString(42) // will return false
For further explanations see the docs.
Upvotes: 4