我正在挖掘新的 scala 反射 api,但无法弄清楚为什么以下代码片段不能按预期工作。给定层次结构(尽力简化):
import scala.reflect.runtime.universe._
trait TF[A] {
implicit def t: TypeTag[A]
def f[T <: A: TypeTag]: PartialFunction[Any, A] = {
case msg: T if typeOf[T] =:= typeOf[A] => msg
}
}
class TFilter[T: TypeTag] extends TF[T] {
def t = typeTag[T]
}
case class Foo(x: Int)
我期待方法f
过滤给定类型的对象。所以下面的代码片段应该返回Seq[Foo]
val messages = Seq(1, "hello", Foo(1))
val tFilter = new TFilter[Foo]
messages collect tFilter.f[Foo]
它实际上返回Seq[Foo]
但其他消息未经过滤,这听起来像是一个错误。
res1: Seq[Foo] = List(1, hello, Foo(1))
Question。我正在使用吗TypeTag
错误还是新反射API的缺陷?
PS0。尝试过Scala 2.10.0-RC1
and 2.10.0-RC2
PS1。解决方法是更换TypeTag
with Manifest
,所以用下面的代码collect
按顺序将返回List(Foo(1))
正如预期的那样。
trait MF[A] {
implicit def m: Manifest[A]
def f[T <: A: Manifest]: PartialFunction[Any, A] = {
case msg: T if typeOf[T] =:= typeOf[A] => msg
}
}
class MFilter[T: Manifest] extends MF[T] {
def m = manifest[T]
}
Update: 和新的一样Scala 2.10.0-RC2
发布。