你能摆脱 Groovy 的“每个"吗?关闭? [英] Can you break from a Groovy "each" closure?
问题描述
是否可以从 Groovy .each{Closure}
中break
,还是应该使用经典循环?
Is it possible to break
from a Groovy .each{Closure}
, or should I be using a classic loop instead?
推荐答案
不,你不能在不抛出异常的情况下中止每个".如果您希望在特定条件下中断中断,您可能需要经典循环.
Nope, you can't abort an "each" without throwing an exception. You likely want a classic loop if you want the break to abort under a particular condition.
或者,您可以使用find"闭包而不是 each 并在您休息时返回 true.
Alternatively, you could use a "find" closure instead of an each and return true when you would have done a break.
此示例将在处理整个列表之前中止:
This example will abort before processing the whole list:
def a = [1, 2, 3, 4, 5, 6, 7]
a.find {
if (it > 5) return true // break
println it // do the stuff that you wanted to before break
return false // keep looping
}
打印
1
2
3
4
5
但不打印 6 或 7.
but doesn't print 6 or 7.
使用接受闭包的自定义中断行为编写自己的迭代器方法也非常容易:
It's also really easy to write your own iterator methods with custom break behavior that accept closures:
List.metaClass.eachUntilGreaterThanFive = { closure ->
for ( value in delegate ) {
if ( value > 5 ) break
closure(value)
}
}
def a = [1, 2, 3, 4, 5, 6, 7]
a.eachUntilGreaterThanFive {
println it
}
也打印:
1
2
3
4
5
这篇关于你能摆脱 Groovy 的“每个"吗?关闭?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!