Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reinterpret List[Any] as a List[Int]

I have a List that I am sure only contains Int members, but the list is of type List[Any]. I need to sum the numbers in this list, but I can't 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 converting it to a List[Int] via l.map(_.toInt) but that of course failed for the exact same reason.

Given a List[Any] that is actually a list of ints, how can I convert it to a List[Int]?

For the curious, this is 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))
like image 373
Cory Klein Avatar asked Dec 12 '22 00:12

Cory Klein


1 Answers

The safest way to cast elements of a list is to use collect:

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

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

collect both filters and maps elements of a list, so any elements which are not ints will be ignored. Only those elements which match the case statement will be included.

OTOH, the best way to fix this is to never have a List[Any] in the first place. I'd address that rather than trying to cast.

like image 113
Ryan Avatar answered Jan 01 '23 08:01

Ryan