我發現這個代碼片段:.delegate在groovy中意味着什麼?
def say = {println m}
say.delegate = [m:2]
say()
這apperantly打印2.它是如何工作的?哪裏可以找到有關.delegate
的文檔? Google讓我進入了代表轉換頁面,根本沒有提到.delegate
。
我發現這個代碼片段:.delegate在groovy中意味着什麼?
def say = {println m}
say.delegate = [m:2]
say()
這apperantly打印2.它是如何工作的?哪裏可以找到有關.delegate
的文檔? Google讓我進入了代表轉換頁面,根本沒有提到.delegate
。
閉包的委託是一個對象,用於解析在閉包本身內部無法解析的引用。如果您的例子是這樣寫的,而不是:
def say = {
def m = 'hello'
println m
}
say.delegate = [m:2]
say()
它打印「你好」,因爲m
可以封閉內解決。然而,當m
封閉內沒有被定義,
def say = {
println m
}
say.delegate = [m:2]
say()
的delegate
用於解析的引用,並且在這種情況下,delegate
是Map
映射封閉件的m
至2
一個方便的方法來爲閉包提供默認參數:'def say = {def m = m?:'hello' ; println m}' – coderatchet
@thenaglecode我認爲你的意思是這樣的 'def say = {def m = it?:'hello'; println m}' –
三個屬性是此,所有者和委派,通常代表被設置爲所有者
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
默認情況下可能是所有者,但驅動Groovy DSLs的是事實,您可以將委託重新分配給任何對象 –
然而,谷歌第二頁確實有它的文檔:http://groovy.codehaus.org/Closures#Closures-this%2Cowner%2Canddelegate。希望這可以幫助。 – Esailija
http://mrhaki.blogspot.com/2009/11/groovy-goodness-setting-closures.html –