groovy中.delegate意味着什么? [英] What does .delegate mean in groovy?

查看:141
本文介绍了groovy中.delegate意味着什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  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 可以在闭包中解析。然而,当 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆