2016-04-30 69 views
0

我是Groovy的新手,我正在學習官方文檔中的閉包。 The 'delegate of a closure' topic給出了例子波紋管:爲什麼這個閉包調用不會以遞歸調用結束?

enter image description here

所以,在5號,我知道委託設置默認爲業主,在該情況下是封閉的封閉enclosed

那麼,爲什麼叫

{ -> delegate }.call() 

enclosed關閉了遞歸調用並沒有結束裏面?看起來像遞歸給我,但如果你運行代碼,不是遞歸。我在這裏錯過了什麼?

回答

2
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()被調用。 :)它現在描繪出一幅清晰的圖畫嗎?

+0

你能否在你的回答中提供@Emmanuel Rosa在他的回答中所做的觀察:在遞歸調用發生時,我們需要'{ - > delegate} .call()。call()'?我認爲這對於這個問題非常重要。謝謝! – reinaldoluckman

+0

我同意,但我認爲這與首先提出的問題無關。問題是「我錯過了什麼?」。答案是關於閉包如何工作的理解。毫無疑問,.call()。call()會導致遞歸,但是整個代碼塊將毫無意義。此外,你如何確保(除了查看代碼).call()返回一個'Closure',你可以再次調用.call()。如果你首先檢查.call()'instanceof' Closure然後make .call()會更好。如果我已經幫助過你,我很高興。 – dmahapatro

2

enclosed閉包中調用{ -> delegate }.call()不會導致遞歸調用,因爲call()在不同的閉包上被調用;在enclosed中創建的一個。要獲得遞歸調用,您可以這樣做:{ -> delegate }.call().call()。第一個call()返回enclosed,第二個調用它。

相關問題