Is it possible to break from a Groovy .each{Closure}, or should I be using a classic loop instead?
Is it possible to break from a Groovy .each{Closure} , or should I be
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Nope, you can’t abort an “each” without throwing an exception. You likely want a classic loop if you want the break to abort under a particular condition.
Alternatively, you could use a “find” closure instead of an each and return true when you would have done a break.
This example will abort before processing the whole list:
Prints
but doesn’t print 6 or 7.
It’s also really easy to write your own iterator methods with custom break behavior that accept closures:
Also prints: