[英]Scala collect type pattern and type erasure
让
val a = List ("a", 1, 2.34, "b", List(6,7))
a: List[Any] = List(a, 1, 2.34, b, List(6, 7))
所以
a.collect { case s: String => s }
res: List[String] = List(a, b)
然而
a.collect { case s: List[Int] => s }
警告
non-variable type argument Int in type pattern List[Int] is unchecked
since it is eliminated by erasure
a.collect { case s: List[Int] => s }
^
res: List[List[Int]] = List(List(6, 7))
因此,请问是否有一种无警告/正确的方法来收集整数列表。
非常感谢。
在JVM上,运行时没有足够的信息来知道List是否为List [Int]。 甚至List [Any]也可能恰好只包含Ints,而且绝对没有办法告诉它具有哪种编译时类型。 但是,您可以编写以下几项代码之一:
对于a中的每个列表,得出为Ints的子集。
产生仅包含整数的列表。
与#1相同,但消除了空白列表。
例如,#1可以编码为
a collect { case list:List[_] => list collect { case x:Int => x } }
作为@AmigoNico答案的补充,有一些实用函数将所有这些封装在干净的,类型安全的函数之后,例如Shapeless的Typeable
类型类。
使用无形2.0.0-M1:
scala> val a = List ("a", 1, 2.34, "b", List(6,7))
a: List[Any] = List(a, 1, 2.34, b, List(6, 7))
scala> import syntax.typeable._
import syntax.typeable._
scala> a.flatMap(_.cast[List[Int]])
res0: List[List[Int]] = List(List(6, 7))
scala> a.flatMap(_.cast[List[String]])
res1: List[List[String]] = List()
请参见无形状特征概述中的键入安全铸造 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.