我正在尝试按项目类型过滤列表。工作代码在这里:
trait Action
class AAA extends Action
class BBB extends Action
val list = List(new AAA, new BBB, new AAA)
def find[T <: Action] = list.filter(_.isInstanceOf[T])
find[AAA]
它没有按预期工作,请参阅输出:
scala> def find[T <: Action] = list.filter(_.isInstanceOf[T])
<console>:11: warning: abstract type T is unchecked since it is eliminated by erasure
def find[T <: Action] = list.filter(_.isInstanceOf[T])
^
find: [T <: Action]=> List[Action]
scala> find[AAA]
res0: List[Action] = List(AAA@2b9cbeec, BBB@3fba8e52, AAA@70d5ca2d)
如何解决?
答案 0 :(得分:2)
您可以使用ClassTag
:
def find[T <: Action : ClassTag] =
list.filter{ implicitly[ClassTag[T]].runtimeClass.isInstance }
scala> find[AAA]
res0: List[Action] = List(AAA@145332ca, AAA@135cfef8)
最好使用collect
方法:
list.collect{ case e: AAA => e }
答案 1 :(得分:0)
使用implicit m:scala.reflect.Manifest[T]
def find[T <: Action](implicit m:scala.reflect.Manifest[T]) =
list.filter{x:Any => m.erasure.isInstance(x)}.asInstanceOf[List[T]]