The basic pseudo code ran in eachLine
is:
while (true) {
def line = readLineFromFile()
if (line==null) {
break
}
closure(line, count++)
}
So there is nothing else, than the end of the file, to stop. Your return
in the closure works, but it returns just from the closure.
For details see the source of org.codehaus.groovy.runtime.IOGroovyMethods.eachLine
.
Closures are not language constructs like while
or for
. They are just passed in anonymous functions with context. It gets more clear, if you write it out, what the code actually means (no groovy shortcuts): inputFile.eachLine({it,i->...})
(note the () from the method call here)
In general: each.*
in groovy does not care for the result of your closure. A return in the closure just means an early bail out (in your case it's a no-op).
So for the general question, can you break
from closures? "No". Iff your caller works with the result, state, ... of the closure in any way to allow you to break from it (e.g. [].find()
does: iterate the list, until the closure returns true, then return the element), you are not able to (well you can throw an exception).