views:

2224

answers:

5

I would like to return from a closure, like one would if using a break statement in a loop.

For example:

largeListOfElements.each{ element->
    if(element == specificElement){
        // do some work          
        return // but this will only leave this iteration and start the next 
    }
}

In the above if statement I would like to stop iterating through the list and leave the closure to avoid unnecessary iterations.

I've seen a solution where an exception is thrown within the closure and caught outside, but I'm not too fond of that solution.

Are there any solutions to this, other than changing the code to avoid this kind of algorithm?

+1  A: 

I think you're working on the wrong level of abstraction. The .each block does exactly what it says: it executes the closure once for each element. What you probably want instead is to use List.indexOf to find the right specificElement, and then do the work you need to do on it.

John Feminella
+1  A: 

best pattern for simulating continue in groovy closure has examples also for break

dfa
+3  A: 

I think you want to use find instead of each (at least for the specified example). Closures don't directly support break.

Under the covers, groovy doesn't actually use a closure either for find, it uses a for loop.

Alternatively, you could write your own enhanced version of find/each iterator that takes a conditional test closure, and another closure to call if a match is found, having it break if a match is met.

Here's an example:

Object.metaClass.eachBreak = { ifClosure, workClosure ->
    for (Iterator iter = delegate.iterator(); iter.hasNext();) {
        def value = iter.next()
        if (ifClosure.call(value)) {
            workClosure.call(value)
            break
        }        
    }
}

def a = ["foo", "bar", "baz", "qux"]

a.eachBreak( { it.startsWith("b") } ) {
    println "working on $it"
}

// prints "working on bar"
Ted Naleid
A: 

If you want to process all elements until a specific one was found you could also do something like this:

largeListOfElements.find { element ->
    // do some work
    element == specificElement
}

Although you can use this with any kind of "break condition". I just used this to process the first n elements of a collection by returning

counter++ >= n

at the end of the closure.

Machisuji
+1  A: 

As I understand groovy, the way to shortcut these kinds of loops would be to throw a user-defined exception. I don't know what the syntax would be (not a grrovy programmer), but groovy runs on the JVM so it would be something something like:

class ThisOne extends Exception {Object foo; ThisOne(Object foo) {this.foo=foo;}}

try { x.each{ if(it.isOk()) throw new ThisOne(it); false} }
catch(ThisOne x) { print x.foo + " is ok"; }     
paulmurray