2011-11-14 58 views
35

我發現這個代碼片段:.delegate在groovy中意味着什麼?

def say = {println m} 
say.delegate = [m:2] 
say() 

這apperantly打印2.它是如何工作的?哪裏可以找到有關.delegate的文檔? Google讓我進入了代表轉換頁面,根本沒有提到.delegate

+0

然而,谷歌第二頁確實有它的文檔:http://groovy.codehaus.org/Closures#Closures-this%2Cowner%2Canddelegate。希望這可以幫助。 – Esailija

+2

http://mrhaki.blogspot.com/2009/11/groovy-goodness-setting-closures.html –

回答

54

閉包的委託是一個對象,用於解析在閉包本身內部無法解析的引用。如果您的例子是這樣寫的,而不是:

def say = { 
    def m = 'hello' 
    println m 
} 
say.delegate = [m:2] 
say() 

它打印「你好」,因爲m可以封閉內解決。然而,當m封閉內沒有被定義,

def say = { 
    println m 
} 
say.delegate = [m:2] 
say() 

delegate用於解析的引用,並且在這種情況下,delegateMap映射封閉件的m至2

+0

一個方便的方法來爲閉包提供默認參數:'def say = {def m = m?:'hello' ; println m}' – coderatchet

+2

@thenaglecode我認爲你的意思是這樣的 'def say = {def m = it?:'hello'; println m}' –

11

三個屬性是此,所有者和委派,通常代表被設置爲所有者

def testClosure(closure) { 
    closure() 
} 
testClosure() { 
    println "this is " + this + ", super:" + this.getClass().superclass.name 
    println "owner is " + owner + ", super:" + owner.getClass().superclass.name 
    println "delegate is " + delegate + ", super:" + delegate.getClass().superclass.name 

    testClosure() { 
    println "this is " + this + ", super:" + this.getClass().superclass.name 
    println "owner is " + owner + ", super:" + owner.getClass().superclass.name 
    println "delegate is " + delegate + ", super:" + delegate.getClass().superclass.name 
    } 
} 

打印

this is [email protected], super:groovy.lang.Script 
owner is [email protected], super:groovy.lang.Script 
delegate is [email protected], super:groovy.lang.Script 
this is [email protected], super:groovy.lang.Script 
owner is [email protected], super:groovy.lang.Closure 
delegate is [email protected], super:groovy.lang.Closure 
+4

默認情況下可能是所有者,但驅動Groovy DSLs的是事實,您可以將委託重新分配給任何對象 –