The Kotlin standard library contains a lot of helper functions on top of the Java standard library for our convenience.
Some of those functions help us in converting between different data types.
For example, the
String.toInt() function converts a number formatted as
String to its
But how do we accomplish the same with a
Char? Spoiler alert: NOT by using
String.toInt() function is basically an extension function to provide a shorthand notation for the Java method
The implementation actually simply delegates to that method:
val numbers: String = "123" val numbersAsInt = numbers.toInt() // Same as: Integer.parseInt(numbers) println("$numbersAsInt") // prints "123"
Char.toInt() has the same signature as the function defined in
String, it is tempting to expect the same behaviour.
However, this is not the case! Instead of converting the character to its numeric value (e.g. '3' → 3),
it actually casts the
Char to the corresponding
Int ASCII value, like casting a Java
char to an
(similar to what
Long.toInt() also does):
val number: Char = '3' val numberAsInt = number.toInt() println("$numberAsInt") // prints "51"
To perform the conversion in the way we want, similar to
we can use the Java method
val numberAsIntCorrect = Character.getNumericValue(number) println("$numberAsIntCorrect") // prints "3"
Fun fact: this works for other numeral types as well (like Unicode roman numerals):
val romanNumeral = '\u216b' println(romanNumeral) // prints: Ⅻ println(Character.getNumericValue(romanNumeral)) // prints: 12
Compiled and tested with Kotlin version 1.3.50.