Scala 使用带有collect的类型

Scala 使用带有collect的类型,scala,types,type-erasure,Scala,Types,Type Erasure,我正在尝试根据类型动态筛选(或收集)列表: 如果我显式地指定了类型,它就可以正常工作 scala> var aList = List("one", 2, 3.3) aList: List[Any] = List(one, 2, 3.3) scala> aList.collect{case x:Int => x} res10: List[Int] = List(2) 如果我想编写一个方法来一般地执行此操作,那么它不会: scala> def collectType[T]

我正在尝试根据类型动态筛选(或收集)列表:

如果我显式地指定了类型,它就可以正常工作

scala> var aList = List("one", 2, 3.3)
aList: List[Any] = List(one, 2, 3.3)

scala> aList.collect{case x:Int => x}
res10: List[Int] = List(2)
如果我想编写一个方法来一般地执行此操作,那么它不会:

scala> def collectType[T](l:List[Any]):List[T] = l.collect{case x:T => x}
warning: there were unchecked warnings; re-run with -unchecked for details
collectType: [T](l: List[Any])List[T]

scala> collectType[Int](aList)
res11: List[Int] = List(one, 2, 3.3)

scala> collectType[Double](aList)  
res16: List[Double] = List(one, 2, 3.3)

scala> collectType[String](aList)
res14: List[String] = List(one, 2, 3.3)
起初,我认为它是将类型命名为“Integer”,而不是使用Integer作为类型,但情况似乎并非如此:

collectType[Int](aList).foreach(x => println(x))
java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
这就好像它推迟了对类型的检查,直到它被迫这样做

关于类型,我遗漏了什么

有没有办法实现我想要的目标


在阅读了相关的问题之后,这就是我想到的。有人指出,这很简单。Taggable是一种特性,它知道如何保存类的标记映射

def matches[F <: Taggable](thing:Taggable)(implicit m:Manifest[F]):Boolean = {
  thing match {
    case e if (m >:> singleType(e)) => true
    case x => false
  }
}
def findByType[G <: Taggable](list:List[Taggable])(implicit m:Manifest[G]) = {
  list.collect{case x if (matches[G](x)) => x}
}
def匹配[F:>singleType(e))=>true
案例x=>false
}
}
def findByType[G x}
}
您丢失了。在运行时,您的方法实际上是

def collectType(l:List):List = l.collect {case x:Object => x}

谢谢,是的,我终于找到了一个与我刚才的问题类似的问题(我之前搜索了很多,诚实!只是没有找到正确的单词组合)Alexey答案中的链接还表明,您可以通过将类型具体化为运行时
Manifest
对象来解决类型擦除问题。@CPJ:最好将其添加到问题的末尾。注释中的多行代码非常不可读。
警告:存在未选中的警告;请使用-unchecked重新运行以了解详细信息