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 Int representation. But how do we accomplish the same with a Char? Spoiler alert: NOT by using Char.toInt(), but by using Char.digitToInt()!

The String.toInt() function is basically an extension function to provide a shorthand notation for the Java method Integer.parseInt(…​). 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"

As 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 int (similar to what Double.toInt() or Long.toInt() also does):

val number: Char = '3'
val numberAsInt = number.toInt()
println("$numberAsInt") // prints "51"
[Update] In Kotlin version 1.5 an extension function has been added to the Standard Library, which provides an easier solution: Char.digitToInt(). The article has been updated below to reflect this change.

To perform the conversion in the way we want, similar to String.toInt(), we can use the extension function Char.digitToInt():

val numberAsIntCorrect = number.digitToInt()
println("$numberAsIntCorrect") // prints "3"

If you are using a Kotlin version older than 1.5.x, you can use the Java method Character.getNumericValue(…​) instead:

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.

shadow-left