• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

breaking from each closure

 
Ranch Hand
Posts: 8945
Firefox Browser Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
author
Posts: 25
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
author
Posts: 77
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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: 8945
Firefox Browser Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
pie sneak
Posts: 4727
Mac VI Editor Ruby
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
reply
    Bookmark Topic Watch Topic
  • New Topic