.delegate 在 groovy 中是什么意思? [英] What does .delegate mean in groovy?
问题描述
我找到了这个代码片段:
I found this code snippet:
def say = {println m}
say.delegate = [m:2]
say()
这显然打印了 2.它是如何工作的?在哪里可以找到关于 .delegate
的文档?Google 将我带到了完全没有提及 .delegate
的 Delegate Transformation 页面.
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()
它打印 'hello',因为 m
可以在闭包内解析.然而,当 m
没有在闭包中定义时,
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()
delegate
用于解析引用,在这种情况下,delegate
是一个映射 m的
Map
代码>到2.
the delegate
is used to resolve the reference, and in this case the delegate
is a Map
that maps m
to 2.
这篇关于.delegate 在 groovy 中是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!