Masupilami
Masupilami

Reputation: 111

Convert List[Any] to List[Int]

How can I convert

List(1, 2, "3")

to

List(1, 2, 3)

since List(1, 2, "3") is of type List[Any] and I can't use .toInt on Any.

Upvotes: 10

Views: 27635

Answers (2)

Xavier Guihot
Xavier Guihot

Reputation: 61774

Starting Scala 2.13 and the introduction of String#toIntOption, we can make @liosedhel's answer a bit safer if needs be:

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

Upvotes: 2

liosedhel
liosedhel

Reputation: 518

That should be sufficient solution:

l.map(_.toString.toInt)

Upvotes: 25

Related Questions