【发布时间】:2015-08-07 14:06:14
【问题描述】:
由于闭包的行为类似于内联方法(我猜,从技术上讲,闭包被编译为类),我没有找到如何在 Groovy 中从闭包返回方法。
例如,如果我没有使用闭包,从main() 调用下面的方法应该只打印 1,但使用闭包它会打印所有 1、2、3:
public static returnFromClosure()
{
[1,2,3].each{
println it
if (it == 1)
return
}
}
我怎样才能实现这种行为?
编辑
问题已作为重复问题关闭。
我的问题是关于一般的关闭。我举了each{} 循环的例子,它涉及到闭包。我知道关于在each{} 循环中使用break 和continue 的问题存在,但这将涉及中断该循环或继续循环的下一次迭代,而不是返回调用代码。这种误解背后的罪魁祸首似乎是我上面给出的例子。然而,在任何循环中使用return 与使用break 不同。我最好给出不同的例子。在这里,简单的关闭:
static main(def args)
{
def closure1 = {
println 'hello';
return; //this only returns this closure,
//not the calling function,
//I was thinking if I can make it
//to exit the program itself
println 'this wont print'
}
closure1();
println 'this will also print :('
}
【问题讨论】:
标签: design-patterns groovy closures