groovy中.delegate意味着什么? [英] What does .delegate mean in groovy?
问题描述
def say = {println m}
say.delegate = [m :2]
say()
哪里可以找到有关 .delegate
的文档? Google让我进入了Delegate Transformation页面,该页面根本没有提及 .delegate
。
闭包的委托是一个对象,用于解析在闭包本身内部无法解析的引用。如果你的例子是这样写的:
def say = {
def m ='hello'
println m
say.delegate = [m:2]
say()
它会打印'hello',因为 m
可以在闭包中解析。然而,当
def say = {
println m
}
say.delegate = [m:2]
say()
使用委托
来解析引用,在这种情况下,委托
是一个 Map
,它将 m
映射到2。
I found this code snippet:
def say = {println m}
say.delegate = [m:2]
say()
That apperantly prints 2. How does it work? Where can find documentation about .delegate
? Google led me to the Delegate Transformation page that doesn't mention .delegate
at all.
The delegate of a closure is an object that is used to resolve references that cannot be resolved within the body of the closure itself. If your example was written like this instead:
def say = {
def m = 'hello'
println m
}
say.delegate = [m:2]
say()
It prints 'hello', because m
can be resolved within the closure. However, when m
is not defined within the closure,
def say = {
println m
}
say.delegate = [m:2]
say()
the delegate
is used to resolve the reference, and in this case the delegate
is a Map
that maps m
to 2.
这篇关于groovy中.delegate意味着什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!