加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

scala – 使用带有collect的Type

发布时间:2020-12-16 09:05:25 所属栏目:安全 来源:网络整理
导读:我正在尝试根据类型动态过滤(或收集)列表: 如果我这样做明确指定类型,它工作正常 scala var aList = List("one",2,3.3)aList: List[Any] = List(one,3.3)scala aList.collect{case x:Int = x}res10: List[Int] = List(2) 如果我想编写一个方法来执行此操作,
我正在尝试根据类型动态过滤(或收集)列表:

如果我这样做明确指定类型,它工作正常

scala> var aList = List("one",2,3.3)
aList: List[Any] = List(one,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,3.3)

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

scala> collectType[String](aList)
res14: List[String] = List(one,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}
}

解决方法

你缺少 type erasure.在运行时你的方法实际上是

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读