| Author |
breaking from each closure
|
Pradeep bhatt
Ranch Hand
Joined: Feb 27, 2002
Posts: 8836
|
|
I am doing some calculation by iterating though a loop.
list.each{
}
When some condition to exit from loop . Having break statement is giving me a compile error.
|
Groovy
|
 |
Peter Ledbrook
author
Greenhorn
Joined: Jul 15, 2009
Posts: 25
|
|
Hi,
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:
Cheers,
Peter
|
 |
Dave Klein
author
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.
Dave
|
Author of Grails: A Quick-Start Guide
|
 |
Pradeep bhatt
Ranch Hand
Joined: Feb 27, 2002
Posts: 8836
|
|
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
Sheriff
Joined: Feb 05, 2003
Posts: 4695
|
|
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.
|
 |
 |
|
|
subject: breaking from each closure
|
|
|