Amir Afghani Amir Afghani - 2 months ago 18
Scala Question

Scala conversion of Strings

When I run the following program :

object Problem {
def main(args: Array[String]) = {
val v = 53.toString
val w = v(0).toInt
println(w)
}
}


it prints out
53
, instead of what I would have expected,
5
. Can someone help me understand why?

UPDATE: The same thing happens if I use
charAt
instead of the array syntax

Answer

53 is the ASCII value for the character '5'. Try 63.toString and you'll see 54 after v(0).toInt.

Use .asDigit to convert a Char to it's Int value. In other words, '5'.toInt == 53 but '5'.asDigit == 5.

Comments