Part 02 / Topic 6 of 8
Converting between types on purpose
Kotlin never converts a value's type for you — not widening (Int → Long), not narrowing
(Double → Int), not text to numbers. Every conversion is a named function you call on purpose,
and section 2 already showed the two numeric ones: .toLong() to widen, .toInt() to narrow (and
truncate). Converting text into a number works the same way, just starting from String:
fun main() {
val n = "42 ".toInt()
println(n)
}
$ kotlinc TrimCheck.kt -include-runtime -d trim.jar
$ java -jar trim.jar
Exception in thread "main" java.lang.NumberFormatException: For input string: "42 "
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67)
at java.base/java.lang.Integer.parseInt(Integer.java:662)
at java.base/java.lang.Integer.parseInt(Integer.java:778)
at TrimCheckKt.main(TrimCheck.kt:2)
at TrimCheckKt.main(TrimCheck.kt)
.toInt() and .toDouble() expect the string to contain only a valid number — a stray
trailing space from a copy-pasted value is enough to fail it. .trim() (removes leading/trailing
whitespace) before converting is the habit to build now; section 7's input reading relies on it.
🔍 Going deeper: Kotlin also has
"42".toIntOrNull(), which returnsnullinstead of throwing on bad input. Using it well needs the nullable-type tools (?.,?:) Part 3 teaches next; this part sticks to the throwing form and a plain.trim().
Done here? The practice set for Part 2 — including the solutions — is on the part page.