What def Keyword Does?
def is a replacement for a type name. In variable definitions it is used to indicate that you don’t care about the type. In variable definitions it is mandatory to either provide a type name explicitly or to use “def” in replacement. This is needed to make variable definitions detectable for the Groovy parser.You can think of def as an alias of Object and you will understand it in an instant.
def name = "Stephanie" println name.toUpperCase() // no cast required
while you would need an explicit cast in the Java version
Object name = "Stephanie"; System.out.println(((String) name).toUpperCase());
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”
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.