Sudha
Sudha

Reputation: 339

Scala - for loop on a string

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.

Upvotes: 2

Views: 545

Answers (2)

Mike Allen
Mike Allen

Reputation: 8249

"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

Upvotes: 5

themathmagician
themathmagician

Reputation: 505

Scala can convert a Char to an Int, as you can see here:

scala> 'H'.toInt
res0: Int = 72

But there is no implicit conversion from String to Int

scala> "H".toInt
java.lang.NumberFormatException: For input string: "H"

In your for loop, you are assigning a Char to e.

Upvotes: -1

Related Questions