简体   繁体   中英

Why kotlin split() and map(String::toInt) on empty string gets NumberFormatException?

Below kotlin code throws the exception.

"".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)

I could not figure the reason since the "".split(";") would return an empyt list that should not call map's callback function.

So, I did some experiments in Kotlin REPL, map on emptyList runs okay.

"".split(";")
res60: kotlin.collections.List<kotlin.String> = []

listOf<String>().map(String::toInt)
res61: kotlin.collections.List<kotlin.Int> = []

Can anyone give me a clue? Thank you.

The list returned by split will always have at least one element. If the delimiter doesn't appear in the String, the returned list will just have the original String in it. It will never return an empty list.

Like Tenfour04 says, the list isn't empty - I'm posting this as an answer so I can do the formatting, but:

println("Empty list: " + listOf<String>())
println("Single empty string: " + listOf(""))
println("Split empty string, plus an extra empty string: " + "".split(';').plus(""))

gives you

Empty list: []
Single empty string: []
Split empty string, plus an extra empty string: [, ]

yeah that's not exactly helpful output

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM