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

标签 list scala types casting type-conversion

我有一个 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)(_ + _)
                              ^

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

给定一个实际上是整数列表的 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]。我会解决这个问题而不是试图转换。

关于list - 将 List[Any] 重新解释为 List[Int],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29149848/

相关文章:

Python字典: Return First Value in List Or String

scala - 为什么 sbt 在 Play 项目中报告 "value enablePlugins is not a member of sbt.Project"?

swift - 这个函数参数是做什么用的?

haskell - 为什么 `(\x y -> x + y) @Integer`失败,但 `(+) @Integer`成功?

c++ - 嵌套的 STL 列表

python - 在字典中的列表中以某种方式复制值

python - 在 python 中搜索字典列表

java - 使用第二个列表作为键过滤 Scala 元组列表(元组内)

scala - 案例类构造函数似乎是虚假的 "does not take arguments"错误

haskell - 所有函数类型都形成 `Hask` 的子类别吗?