JasonG
JasonG

Reputation: 5962

Why does scala (1 to 1000).foreach throw an exception in this case?

In the 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)

Upvotes: 7

Views: 4132

Answers (2)

Lee
Lee

Reputation: 144136

Strings in scala can be used like functions from an index to the char at the given index:

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

This is a general mechanism in Scala where an object with an apply method can be treated like a function. The apply method for strings is defined in StringOps.

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

Upvotes: 7

om-nom-nom
om-nom-nom

Reputation: 62835

Treat code below as unwrapped pseudocode:

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

Upvotes: 12

Related Questions