将 List[Any] 重新解释为 List[Int]

Reinterpret List[Any] as a List[Int]

我有一个 List,我确信它只包含 Int 个成员,但列表的类型是 List[Any]。我需要对这个列表中的数字求和,但我不能使用 + 运算符,因为它没有在 Any.

上定义
scala> val l = List[Any](1, 2, 3)
l: List[Any] = List(1, 2, 3)

scala> l.foldLeft(0)(_ + _)
<console>:9: error: overloaded method value + with alternatives:
  (x: Int)Int <and>
  (x: Char)Int <and>
  (x: Short)Int <and>
  (x: Byte)Int
 cannot be applied to (Any)
              l.foldLeft(0)(_ + _)
                              ^

我尝试通过 l.map(_.toInt) 将其转换为 List[Int],但由于完全相同的原因当然失败了。

给定一个 List[Any] 实际上是一个整数列表,我如何将它转换为 List[Int]

出于好奇,我是这样来到这里的:

scala> val l = List(List("x", 1), List("y", 2))
l: List[List[Any]] = List(List(x, 1), List(y, 2))

scala> l.transpose
res0: List[List[Any]] = List(List(x, y), List(1, 2))

转换列表元素的最安全方法是使用 collect:

val l: List[Any] = List(1, 2, 3)

val l2: List[Int] = l collect { case i: Int => i }

collect 过滤器和映射列表的元素,因此任何不是整数的元素都将被忽略。仅包含与 case 语句匹配的元素。

OTOH,解决此问题的最佳方法是首先不要使用 List[Any]。我会解决这个问题,而不是尝试投射。