Groovy 方法无法访问封闭范围内的变量 [英] Groovy method cannot access variable in enclosing scope

查看:25
本文介绍了Groovy 方法无法访问封闭范围内的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这就是闭包的用途,但以下不应该也适用吗?:

I know that this is what closures are for, but shouldn't the below work as well?:

def f = 'foo'
def foo() {
   println(f)
}
foo()

结果:

Caught: groovy.lang.MissingPropertyException: No such property: f for class: bar
groovy.lang.MissingPropertyException: No such property: f for class: bar
   at bar.foo(bar.groovy:4)
   at bar.run(bar.groovy:7)

推荐答案

在 groovy 脚本中(与 class 相对),您的代码本质上等同于:

In a groovy script (as opposed to class), your code is essentially equivalent to:

class ScriptName {
  def main(args) {
    new ScriptName().run(args)
  }

  def run(args) {
    def f = 'foo'
    foo()
  }

  def foo() {
    println(f)
  }
}

由 groovy 为 groovy 脚本创建的隐式"封闭类始终存在,但在您的代码中不可见.上面很明显为什么 foo 方法看不到 f 变量.

the 'implicit' enclosing class created by groovy for groovy scripts is always present but not visible in your code. The above makes it obvious why the foo method does not see the f variable.

你有几个选择

选项 1 - 绑定

有关详细信息,请参阅 关于脚本绑定的 groovy 文档.

See the groovy docs on script bindings for details.

// put the variable in the script binding
f = 'foo'

这是以下的简写:

binding.setVariable('f', 'foo')

对于 groovy 脚本,脚本绑定随处可见,这使得变量本质上是全局的".

where the script binding is visible everywhere for groovy scripts and this makes the variable essentially 'global'.

选项 2 - @Field 注释

有关详细信息,请参阅 关于 Field 注释的 groovy 文档.

See groovy docs on the Field annotation for details.

import groovy.transform.Field
...    
// use the groovy.transform.Field annotation 
@Field f = 'foo' 

Field 注释专门用于为 groovy 脚本提供将字段添加到隐式"封闭类的能力.生成的类将如下所示:

the Field annotation is specifically there to give groovy scripts the ability to add fields to the 'implicit' enclosing class. The generated class would then look something like the following:

class ScriptName {
  def f = 'foo'

  def main(args) {
    new ScriptName().run(args)
  }

  def run(args) {
    foo()
  }

  def foo() {
    println(f)
  }
}

这也基本上使脚本中的变量可以全局"访问.

which also essentially makes the variable accessible 'globally' in the script.

这篇关于Groovy 方法无法访问封闭范围内的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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