Why I can’t convert a String (number with decimal) into Int directly?
Copy code
fun main() {
val stringDouble = "420.0"
val int = stringDouble.toIntOrNull()
assert(int != null) // failed
}
b
Big Chungus
10/20/2020, 7:26 AM
I'm guessing to prevent rounding ambiguity.
j
jbnizet
10/20/2020, 7:26 AM
Because the method would have too many responsibilities: what can be parsed, what cannot? Should it truncate or round? How? It's easier, more readable and more flexible to compose two functions: one that parses the string to a double or BigDecimal, and one that lets you transform this double or BigDecimal to an int, the way you want to.
🙆♂️ 1
➕ 4
n
nanodeath
10/20/2020, 4:20 PM
agree, but also, more simply: it's not an int 🙂
😆 1
➕ 2
s
Simon Lin
10/23/2020, 8:09 AM
it’s not an int
stringDouble.toDouble()
is also not an int. But it can call
toInt()
They got same prefix (toInt*) but do different work.