[英]Why kotlin split() and map(String::toInt) on empty string gets NumberFormatException?
下面的 kotlin 代码抛出异常。
"".split(";").map(String::toInt)
java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:592)
at java.lang.Integer.parseInt(Integer.java:615)
我想不出原因,因为 "".split(";") 会返回一个不应调用地图回调函数的空列表。
所以,我在 Kotlin REPL 中做了一些实验,emptyList 上的 map 运行正常。
"".split(";")
res60: kotlin.collections.List<kotlin.String> = []
listOf<String>().map(String::toInt)
res61: kotlin.collections.List<kotlin.Int> = []
谁能给我一个线索? 谢谢你。
split
返回的列表总是至少有一个元素。 如果分隔符未出现在字符串中,则返回的列表中将只包含原始字符串。 它永远不会返回空列表。
就像 Tenfour04 所说的那样,该列表不是空的 - 我将此作为答案发布,以便我可以进行格式化,但是:
println("Empty list: " + listOf<String>())
println("Single empty string: " + listOf(""))
println("Split empty string, plus an extra empty string: " + "".split(';').plus(""))
给你
Empty list: []
Single empty string: []
Split empty string, plus an extra empty string: [, ]
是的,这并不是很有帮助的输出
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.