Eugene Loy
Eugene Loy

Reputation: 12436

Pattern matching and (ereased) generic function type argument

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

Answers (1)

Martin Ring
Martin Ring

Reputation: 5426

Scala has introduced ClassTags 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

Related Questions