Why scala (1 to 1000). Before throwing an exception in this case?

In repl, this throws an exception, and I don't know why. I would really like to understand this.

scala> (1 until 10000).foreach("%s%s".format("asdf", "sdff")) java.lang.StringIndexOutOfBoundsException: String index out of range: 8 at java.lang.String.charAt(String.java:686) at scala.collection.immutable.StringLike$class.apply(StringLike.scala:54) at scala.collection.immutable.WrappedString.apply(WrappedString.scala:32) at scala.collection.immutable.WrappedString.apply(WrappedString.scala:32) at scala.collection.immutable.Range.foreach(Range.scala:75) 
+6
source share
2 answers

Consider the code below as expanded pseudo-code:

 val str = "%s%s".format("asdf", "sdff") // "asdfsdff" you see, only 8 characters (1 until 10000).foreach(x => str.getCharAt(x)) 
+11
source

Strings in scala can be used as functions from index to char at a given index:

 val s: Int => Char = "abcd" val c: Char = s(1) 

This is a common mechanism in scala where an object with an apply method can be thought of as a function. The apply method for strings is defined in StringOps .

The string "asdfsdff" is passed to foreach, and each subsequent value in the range is passed to the function. This throws an exception when the index reaches 8 , since it is out of range.

+7
source

All Articles