In the scala REPL, when I give "H".toInt, I get NumberFormatException. But, the same thing is working within the for loop - for ( e <- "Hello" ) println ( e.toInt) I want to understand how it works within the for loop but not outside.
2 Answers
"H" is a String, while e is a Char, and the latter are integer values (Unicode code point values) that map to characters; calling .toInt on a Char value simply returns that code point value. A String is a sequence of Char values, and the for loop iterates on each character that makes up the string "Hello" in turn, processing them one at a time:
>scala
Welcome to Scala 2.12.5 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_161).
Type in expressions for evaluation. Or try :help.
scala> "H".toInt
java.lang.NumberFormatException: For input string: "H"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.parseInt(Integer.java:615)
at scala.collection.immutable.StringLike.toInt(StringLike.scala:301)
at scala.collection.immutable.StringLike.toInt$(StringLike.scala:301)
at scala.collection.immutable.StringOps.toInt(StringOps.scala:29)
... 28 elided
scala> for(e <- "Hello") println(e.toInt)
72
101
108
108
111
For example, 72 is the Unicode code point value for the character 'H', 101 for the character 'e', etc.
If you execute 'H'.toInt it will work as it does in the for loop:
scala> 'H'.toInt
res2: Int = 72
When toInt is used on a String, if its value encodes an integer value, then it will work. For example:
scala> "72".toInt
res3: Int = 72
If it doesn't encode an integer value, then you get the NumberFormatException:
scala> "Fred".toInt
java.lang.NumberFormatException: For input string: "Fred"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.parseInt(Integer.java:615)
at scala.collection.immutable.StringLike.toInt(StringLike.scala:301)
at scala.collection.immutable.StringLike.toInt$(StringLike.scala:301)
at scala.collection.immutable.StringOps.toInt(StringOps.scala:29)
... 28 elided
"H"is aString.'H'is aCharso'H'.toIntworks fine.yield: scala-lang.org/files/archive/spec/2.12/….