Convert List [Any] to List [Int]

How can i convert

List(1, 2, "3") 

in

 List(1, 2, 3) 

since List(1, 2, "3") is of type List[Any] and I cannot use .toInt for Any .

+9
scala
source share
2 answers

This should be a sufficient solution:

 l.map(_.toString.toInt) 
+20
source share

Starting with Scala 2.13 and introducing String#toIntOption , we can make @liposedhel's answer more secure if necessary:

 // val l: List[Any] = List(1, 2, "3") l.flatMap(_.toString.toIntOption) // List[Int] = List(1, 2, 3) 
0
source share

All Articles