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

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

问题描述

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

例如:

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

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

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

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

解决方案

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

在幕后,groovy 实际上并不使用闭包来查找,而是使用 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天全站免登陆