我是Groovy的新手,我正在学习官方文档中的闭包。 The 'delegate of a closure' topic给出了例子波纹管:为什么这个闭包调用不会以递归调用结束?
所以,在5号,我知道委托设置默认为业主,在该情况下是封闭的封闭enclosed
。
那么,为什么叫
{ -> delegate }.call()
的enclosed
关闭了递归调用并没有结束里面?看起来像递归给我,但如果你运行代码,不是递归。我在这里错过了什么?
我是Groovy的新手,我正在学习官方文档中的闭包。 The 'delegate of a closure' topic给出了例子波纹管:为什么这个闭包调用不会以递归调用结束?
所以,在5号,我知道委托设置默认为业主,在该情况下是封闭的封闭enclosed
。
那么,为什么叫
{ -> delegate }.call()
的enclosed
关闭了递归调用并没有结束里面?看起来像递归给我,但如果你运行代码,不是递归。我在这里错过了什么?
def enclosed = {
// delegate == owner == enclosed (variable)
{ ->
// When this closure is called return the delegate (enclosed)
delegate
}.call() // Called immediately
// above closure is same as writing
// return delegate
}
// When enclosed in called the delegate is returned immediately
// from the invocation of the inner closure, hence the result of the
// closure call is the closure (delegate) itself
assert enclosed() == enclosed
请记住,无论是假设enclosed
瓶盖内发生不会发生,直到enclosed()
被调用。 :)它现在描绘出一幅清晰的图画吗?
在enclosed
闭包中调用{ -> delegate }.call()
不会导致递归调用,因为call()
在不同的闭包上被调用;在enclosed
中创建的一个。要获得递归调用,您可以这样做:{ -> delegate }.call().call()
。第一个call()
返回enclosed
,第二个调用它。
你能否在你的回答中提供@Emmanuel Rosa在他的回答中所做的观察:在递归调用发生时,我们需要'{ - > delegate} .call()。call()'?我认为这对于这个问题非常重要。谢谢! – reinaldoluckman
我同意,但我认为这与首先提出的问题无关。问题是“我错过了什么?”。答案是关于闭包如何工作的理解。毫无疑问,.call()。call()会导致递归,但是整个代码块将毫无意义。此外,你如何确保(除了查看代码).call()返回一个'Closure',你可以再次调用.call()。如果你首先检查.call()'instanceof' Closure然后make .call()会更好。如果我已经帮助过你,我很高兴。 – dmahapatro