List of reinterpretations [Any] as a list [Int]

I have Listone which, I am sure, contains only Intmembers, but the list is of type List[Any]. I need to sum the numbers in this list, but I cannot use the operator +because it is not defined on 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)(_ + _)
                              ^

I tried to convert it to List[Int]through l.map(_.toInt), but, of course, failed for the same reason.

Given List[Any]which is actually an int list, how can I convert it to List[Int]?

For the curious, here's how I got here:

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))
+4
source share
1 answer

The safest way to cast list items is to use collect:

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

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

collect , , , int, . , case.

OTOH, - List[Any] . , , .

+12

All Articles