blue-sky blue-sky - 2 months ago 8
Scala Question

Conversion between int and char not working as expected

To convert a

char
to its
Int
equivalent I use:

scala> 'a'.asDigit
res2: Int = 10


I expect to convert
10
to char
a
by using
toChar
method:

scala> 10.toChar
res3: Char =


But
a
is not being returned.

How can you convert and un-convert a digit to char?

Nio Nio
Answer

There is a difference between asDigit and toInt. If you want the Int equivalent of 'a' in terms of the Ascii character set then use toInt.

scala> 'a'.toInt
res12: Int = 97

scala> 97.toChar
res13: Char = a

To see why 10.toChar does not print anything check out the character tables.

Comments