Groovy:“def"的目的是什么?在“def x = 0"中? [英] Groovy: what's the purpose of "def" in "def x = 0"?

查看:25
本文介绍了Groovy:“def"的目的是什么?在“def x = 0"中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在以下代码段中(取自 Groovy 语义手册页),为什么要在赋值前加上关键字 def?

In the following piece of code (taken from the Groovy Semantics Manual page), why prefix the assignment with the keyword def?

def x = 0
def y = 5

while ( y-- > 0 ) {
    println "" + x + " " + y
    x++
}

assert x == 5

def 关键字可以删除,此代码段将产生相同的结果.那么关键字 def效果是什么?

The def keyword can be removed, and this snippet would produce the same results. So what's the effect of the keyword def ?

推荐答案

它是基本脚本的语法糖.省略def"关键字会将变量放在当前脚本的绑定中,groovy 将其(主要)视为全局范围的变量:

It's syntactic sugar for basic scripts. Omitting the "def" keyword puts the variable in the bindings for the current script and groovy treats it (mostly) like a globally scoped variable:

x = 1
assert x == 1
assert this.binding.getVariable("x") == 1

使用 def 关键字不会将变量放入脚本绑定中:

Using the def keyword instead does not put the variable in the scripts bindings:

def y = 2

assert y == 2

try {
    this.binding.getVariable("y") 
} catch (groovy.lang.MissingPropertyException e) {
    println "error caught"
} 

打印:错误捕获"

在较大的程序中使用 def 关键字很重要,因为它有助于定义可以找到变量的范围并有助于保持封装.

Using the def keyword in larger programs is important as it helps define the scope in which the variable can be found and can help preserve encapsulation.

如果您在脚本中定义了一个方法,它将无法访问在主脚本主体中使用def"创建的变量,因为它们不在范围内:

If you define a method in your script, it won't have access to the variables that are created with "def" in the body of the main script as they aren't in scope:

 x = 1
 def y = 2


public bar() {
    assert x == 1

    try {
        assert y == 2
    } catch (groovy.lang.MissingPropertyException e) {
        println "error caught"
    }
}

bar()

打印错误捕获"

y"变量不在函数内的作用域内.x"在范围内,因为 groovy 将检查变量的当前脚本的绑定.正如我之前所说,这只是一种语法糖,可以让快速而脏的脚本更快地输入(通常是一行).

The "y" variable isn't in scope inside the function. "x" is in scope as groovy will check the bindings of the current script for the variable. As I said earlier, this is simply syntactic sugar to make quick and dirty scripts quicker to type out (often one liners).

在大型脚本中的良好做法是始终使用def"关键字,这样您就不会遇到奇怪的范围问题或干扰您不打算使用的变量.

Good practice in larger scripts is to always use the "def" keyword so you don't run into strange scoping issues or interfere with variables you don't intend to.

这篇关于Groovy:“def"的目的是什么?在“def x = 0"中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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