scala 将 List[Any] 转换为 List[Int]

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22442470/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 06:06:32  来源:igfitidea点击:

Convert List[Any] to List[Int]

scala

提问by Masupilami

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 .toInton Any.

因为List(1, 2, "3")是类型List[Any],我不能使用.toInton Any

回答by liosedhel

That should be sufficient solution:

那应该是足够的解决方案:

l.map(_.toString.toInt)

回答by Xavier Guihot

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

开始Scala 2.13和引入String#toIntOption,如果需要,我们可以使@liosedhel 的答案更安全一些:

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