由于类型擦除,您的代码基本上等于:
case class C[T]() {
val pf:PartialFunction[Any,Any] = {
case i:Any => i // this matches everything
}
}
您可以使用TypeTags 来修复它:
import scala.reflect.runtime.universe._
case class C[T: TypeTag]() {
def pf[U: TypeTag]: PartialFunction[U, Any] = {
case i if typeOf[U] <:< typeOf[T] => i
}
}
使用中:
@ C[Int]().pf.isDefinedAt("")
res41: Boolean = false
@ C[Int]().pf.isDefinedAt(34)
res42: Boolean = true
这些实际上等于
@ C[Int]().pf[String].isDefinedAt("")
res41: Boolean = false
@ C[Int]().pf[Int].isDefinedAt(34)
res42: Boolean = true
推断类型 U 的地方 - 它有一个限制,即当需要 TypeTag 时,它只能与编译器对类型的了解一样精确。
您也可以尝试使用ClassTag[T] 来使用运行时反射...但对于原语它会失败
case class C[T]()(implicit classTag: scala.reflect.ClassTag[T]) {
def pf[U: TypeTag]: PartialFunction[U, Any] = {
case i if classTag.runtimeClass.isInstance(i) => i
}
}
导致
@ C[Int]().pf.isDefinedAt(34)
res2: Boolean = false
@ C[Int]().pf.isDefinedAt("")
res3: Boolean = false
问题是 classTag 会解析为 Scala 的 int 而运行时会显示 java.lang.Int:
@ case class C[T]()(implicit classTag: scala.reflect.ClassTag[T]) {
def pf: PartialFunction[Any, Any] = {
case i => println(s"T = ${classTag.runtimeClass.getName}, here: ${i.getClass.getName}")
}
}
defined class C
@ C[Int]().pf.isDefinedAt(34)
res7: Boolean = true
@ C[Int]().pf(34)
T = int, here: java.lang.Integer
res8: Any = ()
一般来说这里没有完美的解决方案,你可以阅读更多类似的问题here和here。