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

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

问题描述

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

例如:

largeListOfElements.each{ element->如果(元素 == 特定元素){//做一些工作return//但这只会离开这个迭代并开始下一个迭代}}

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

我见过一个解决方案,在闭包内抛出异常并在外部捕获,但我不太喜欢这种解决方案.

除了更改代码以避免这种算法之外,有什么解决方案吗?

解决方案

我认为您想使用 find 而不是 each(至少对于指定的示例).闭包不直接支持 break.

在幕后,groovy 实际上并没有为 find 使用闭包,而是使用了 for 循环.

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

这是一个例子:

<上一页>Object.metaClass.eachBreak = { ifClosure, workClosure ->for (Iterator iter = delegate.iterator(); iter.hasNext();) {def 值 = iter.next()如果(ifClosure.call(值)){workClosure.call(值)休息}}}def a = ["foo", "bar", "baz", "qux"]a.eachBreak( { it.startsWith("b") } ) {println "正在处理 $it"}//打印工作条"

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?

解决方案

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"

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

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