1

Example:

val double = "   6  ".toDouble()
val int = "   6  ".toInt()

The second declaration causes the following Exception:

Exception in thread "main" java.lang.NumberFormatException: For input string: "   6  "
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67)
at java.base/java.lang.Integer.parseInt(Integer.java:654)
at java.base/java.lang.Integer.parseInt(Integer.java:786)
at MainKt.main(Main.kt:9)

Are there any reasons why they didn't decide to either allow Strings to contain spaces or not for every type of number?

  • 3
    Kotlin just delegates to Java's `Double.parseDouble` and `Integer.parseInt`, so it's a question for the Java language designers. I'm not sure about the reasons, but looking at the source code there's a `trim` while doing `parseDouble` with a comment: `// don't fool around with white space`. Btw [this was asked](https://stackoverflow.com/questions/48669698/difference-in-behaviour-between-double-parsedouble-and-integer-parseint). – gpunto Apr 23 '22 at 20:22
  • I didn't find that question because I searched for the behavior in kotlin, sorry. It seems like toDouble() / parseDouble() was implemented by different developers in a later version of java. Thank you. – konstantin durant Apr 24 '22 at 08:33

0 Answers0