如何从一个groovy闭包返回并停止执行? [英] How does one return from a groovy closure and stop its execution?

查看:950
本文介绍了如何从一个groovy闭包返回并停止执行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从一个闭包返回,就像在循环中使用break语句一样。

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

例如:

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

在上面的if语句中,我想停止遍历列表,并离开闭包以避免不必要的迭代。

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?

推荐答案

我想要使用find而不是每个(至少对于指定的示例)。闭包不直接支持break。

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

在覆盖下,groovy实际上并没有使用闭包或者find,它使用for循环。

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

或者,您可以编写自己的增强版本的find /每个迭代器接受一个条件测试闭包,另一个闭包调用如果找到匹配,如果匹配被满足,它断裂。

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.

这里有一个例子:


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"

这篇关于如何从一个groovy闭包返回并停止执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆