Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

scala

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)
like image 948
JasonG Avatar asked Apr 17 '13 18:04

JasonG


2 Answers

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))
like image 196
om-nom-nom Avatar answered Sep 27 '22 00:09

om-nom-nom


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.

like image 32
Lee Avatar answered Sep 27 '22 00:09

Lee