0

I'm a total Scala newbie and at a loss as to what is going on here:

(1 to 2) foreach {
  println("+")
  v => { println(v) }
  println("-")
}

Why does this print the following?

+
1
-
2
-

I think it has something to do with an instance being created implicitly and the body being executed as the constructor, which would explain the + being printed once. But that doesn't explain why the - is printed after each loop.

I'm sorry if this is a silly question. This just keeps nagging me. Debug execution inside Eclipse didn't reveal anything enlightening either.

And to add to the question: Why is this valid? I've understood that foreach should accept one parameter, a function, which receives an Int and returns, umm.. something.

Gima
  • 1,892
  • 19
  • 23

1 Answers1

2

I believe it is interpreting your code like so:

(1 to 2) foreach {
  println("+")
  v => {{ println(v) }
    println("-")
  }
}

To clarify - foreach takes a single argument of the type being iterated over (so, in this case an Int) and runs the function passed in as an argument to it over that value. In this case, the first println is invoked during the construction of said function. The compiler has to then interpret the rest of the function as something of the form:

v: Int => Unit

which is exactly what it does in your case, the fact that you put an extra set of braces does not change it, you could just as easily have done:

(1 to 2) foreach {
  println("+")
  v => println(v)
    println("-")
}
ishaaq
  • 6,329
  • 3
  • 16
  • 28
  • God of programming help me if it does. A link to the specification saying so would be helpful. – Gima Mar 23 '14 at 22:53
  • @Gima, §6.11 of the [SLS](http://www.scala-lang.org/files/archive/nightly/pdfs/ScalaReference.pdf) deals with blocks. I don't see how else the compiler could interpret your code without considering everything after `v =>` as a single block – ishaaq Mar 23 '14 at 23:41
  • 2
    To clarify a bit more, `foreach` doesn't "take a single argument of the type being iterated over", it takes a function which "takes a single argument" etc. – Alexey Romanov Mar 24 '14 at 05:53
  • 1
    Explaining why braces are unnecessary when a function literal is the result expression of a block: http://stackoverflow.com/a/13873899/1296806 – som-snytt Mar 24 '14 at 05:55