is there a way to 'break' out of a groovy closure.
maybe something like this:
[1, 2, 3].each {
println(it)
if (it == 2)
break
}
is there a way to 'break' out of a groovy closure.
maybe something like this:
[1, 2, 3].each {
println(it)
if (it == 2)
break
}
You can throw an exception:
try {
[1, 2, 3].each {
println(it)
if (it == 2)
throw new Exception("return from closure")
}
} catch (Exception e) { }
Use could also use "findAll" or "grep" to filter out your list and then use "each".
[1, 2, 3].findAll{ it < 3 }.each{ println it }
Take a look at Best pattern for simulating continue in groovy closure for an extensive discussion.
Edited.
[1, 2, 3].each {
if (it == 2) return
println(it)
}
Think of the closure like a little method. How would you break out of a method? You return. Return will break out of the closure.
You cannot break out of the iteration just as you couldn't break out of the following code.
doThings([0,1,3])
void doThings(List things) {
for (i in things) {
printIt(i)
}
}
void printIt(Object it) {
if(it == 2) break // This is not possible beacuse you arn't inside a loop
println it
}
This almost exactly what Groovy is doing when you call the each METHOD and pass it a closure.
Something you might want to consider for your particular case: the find or findAll methods.
[1,2,3].findAll { it < 2 }.each { println it }
I hope this helps you understand what is going on.
I often forget that Groovy implements an "any" method.
[1, 2, 3].any
{
println it
return (it == 2)
}