Scala收集类型模式和类型擦除

Scala收集类型模式和类型擦除,scala,types,erasure,Scala,Types,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 } 因此,询问是否有无警告/正确的方法来收集整数列表 非常感谢。在JVM上

诸如此类

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 }
因此,询问是否有无警告/正确的方法来收集整数列表


非常感谢。

在JVM上,运行时没有足够的信息来知道列表是否是列表[Int]。即使是一个列表[Any]也可能恰好只包含int,而且根本无法判断它是哪种编译时类型。但是,您可以编写以下几件事中的一件:

  • 对于a中的每个列表,生成整数子集

  • 在中生成仅包含整数的列表

  • 与#1相同,但删除空列表

  • 例如#1可以编码为

    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[Int]。即使是一个列表[Any]也可能恰好只包含int,而且根本无法判断它是哪种编译时类型。但是,您可以编写以下几件事中的一件:

  • 对于a中的每个列表,生成整数子集

  • 在中生成仅包含整数的列表

  • 与#1相同,但删除空列表

  • 例如#1可以编码为

    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))
    

    作为@AmigoNico答案的补充,有一些实用函数将所有这些封装在干净的、类型安全的函数后面,例如的
    Typeable
    type类

    使用无形状2.0.0-M1:

    a collect { case list:List[_] => list collect { case x:Int => x } }
    

    请参见shapeless Features overview。

    作为@AmigoNico答案的补充,有一些实用程序函数将所有这些封装在一个干净的、类型安全的函数后面,例如可键入的
    类型类

    使用无形状2.0.0-M1:

    a collect { case list:List[_] => list collect { case x:Int => x } }
    

    请参见无形状功能概述中的。

    非常感谢您给出的清晰答案。非常感谢您给出的清晰答案。