We have digitToIntOrNull()
built-in function to parse digit from a Char :
fun main() {
println('0'.digitToIntOrNull()) // Prints 0
}
Recall that character code of digits lies in the range 48..57
. So, to convert a digit character to Int, we can simple subtract ‘0’.code
or 48
from its code :
fun Char.digitToIntOrNull(): Int? {
return if (this in '0'..'9')
this.code - '0'.code
else
null
}