File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

breaking from each closure

 
Pradeep bhatt
Ranch Hand
Posts: 8927
Firefox Browser Java Spring
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Peter Ledbrook
author
Greenhorn
Posts: 25
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 77
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Pradeep bhatt
Ranch Hand
Posts: 8927
Firefox Browser Java Spring
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 4727
Mac Ruby VI Editor
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic