【发布时间】:2010-10-20 10:03:13
【问题描述】:
我想从闭包中返回,就像在循环中使用 break 语句一样。
例如:
largeListOfElements.each{ element->
if(element == specificElement){
// do some work
return // but this will only leave this iteration and start the next
}
}
在上面的 if 语句中,我想停止遍历列表并离开闭包以避免不必要的迭代。
我见过一个解决方案,在闭包内抛出异常并在外部捕获,但我不太喜欢这种解决方案。
除了更改代码以避免这种算法之外,还有什么解决方案吗?
【问题讨论】: