File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Groovy and the fly likes breaking from each closure Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Languages » Groovy
Bookmark "breaking from each closure" Watch "breaking from each closure" New topic

breaking from each closure

Pradeep bhatt
Ranch Hand

Joined: Feb 27, 2002
Posts: 8927

I am doing some calculation by iterating though a loop.



When some condition to exit from loop . Having break statement is giving me a compile error.

Peter Ledbrook

Joined: Jul 15, 2009
Posts: 25

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:


Dave Klein
Ranch Hand

Joined: Aug 29, 2007
Posts: 77
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.


Author of Grails: A Quick-Start Guide
Pradeep bhatt
Ranch Hand

Joined: Feb 27, 2002
Posts: 8927

Well, actually I was using eachWithIndex. Now I would need to use the Java's enhanced for loop and also declare an integer as I need index or use the traditional for loop. Back to basics.
Marc Peabody
pie sneak

Joined: Feb 05, 2003
Posts: 4727

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.

A good workman is known by his tools.
I agree. Here's the link:
subject: breaking from each closure
It's not a secret anymore!