Groovy: what's the purpose of "def" in "def x = 0"?

Leonel picture Leonel · Oct 8, 2008 · Viewed 86.7k times · Source

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 ?

Answer

Ted Naleid picture Ted Naleid · Oct 9, 2008

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.