Why I can’t convert a String (number with decimal)...
# announcements
s
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
I'm guessing to prevent rounding ambiguity.
j
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
agree, but also, more simply: it's not an int 🙂
😆 1
2
s
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.
n
sorry, I didn't follow that