Groovy:“def”的用途是什么? in“def x = 0”? [英] Groovy: what's the purpose of "def" in "def x = 0"?

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

问题描述

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

  def x = 0 
def y = 5

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

assert x == 5

def 关键字可以被移除,并且这个片段会产生相同的结果。那么关键字 def 效果是什么?

解决方案

它是基本脚本的语法糖。省略def关键字将变量放入当前脚本的绑定中,groovy将它视为一个全局范围的变量:

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

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

  def y = 2 

assert y == 2

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

打印:error caught



在更大的程序中使用def关键字非常重要,因为它有助于定义可以找到变量的范围,并且可以帮助保留封装。 / p>

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
















$ b $ = 1

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

$ b bar()

打印error caught



y变量不在函数内。 x在范围内,因为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

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

解决方案

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

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"
} 

Prints: "error caught"

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.

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()

prints "error caught"

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).

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”的用途是什么? in“def x = 0”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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