This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
The only way I know of to break out of a closure loop like this is to throw an exception - not an elegant solution I'm afraid. Even using the return statement won't help because it exits the closure, but not the each() method.
The usual solution is either to use a more appropriate iterator method, such as find(), or use a standard for loop:
Just to tack onto Peter's reply: I've yet to run into a situation where I couldn't come up with a better solution using more intelligent filtering instead of a break. So, yes, you can use a traditional Java loop with break but the exercise of trying to go without it may help you write better code.
Hi Prad, if you find yourself wanting to use a break statement in an iteration method in Groovy, there's a really good chance you could benefit by using a different iteration method (like find or any).
If you post your code I can help you find the most appropriate method.