Since closures behave like inline methods (I guess, technically closures are compiled to classes), I didnt find how to return a method from closure in Groovy.
For example calling below method from main()
should have printed only 1 if I did not used closure, but with closure it prints all 1, 2, 3:
public static returnFromClosure()
{
[1,2,3].each{
println it
if (it == 1)
return
}
}
How I can achieve this behavior?
Edit
The question was closed as a duplicate.
My question was about closure in general. And I gave example of each{}
loop which involves closure. I know the question about using break
and continue
in each{}
loop are there, but that will deal about breaking that loop or continuing to the next iteration of the loop, but not about returning the calling code. The culprit behind this mis-understanding seems to be the example I gave above. However using return
inside any loop is different from using break
. I better give different example. Here it is, with plain closure:
static main(def args)
{
def closure1 = {
println 'hello';
return; //this only returns this closure,
//not the calling function,
//I was thinking if I can make it
//to exit the program itself
println 'this wont print'
}
closure1();
println 'this will also print :('
}