def ~= Object
As Tim pointed out, def
is not a an alias to Object
data type, but it can be though as one (Object
is a class while def
is just a Groovy keyword) - http://www.groovy-lang.org/semantics.html#_variable_definition The only thing def
has in common with Object
is the fact that on the JVM level every def
statement or type replacement is compiled to Object
,
Consider very simple test.groovy
script with following content:
def name = "John"
String surname = "Doe"
println "$name $surname"
If you compile it to test.class
and take a look at the decompiled code here is what you will see:
Compiled from "test.groovy"
public class test extends groovy.lang.Script {
public static transient boolean __$stMC;
public test();
LocalVariableTable:
Start Length Slot Name Signature
4 4 0 this Ltest;
public test(groovy.lang.Binding);
LocalVariableTable:
Start Length Slot Name Signature
0 9 0 this Ltest;
0 9 1 context Lgroovy/lang/Binding;
public static void main(java.lang.String...);
LocalVariableTable:
Start Length Slot Name Signature
0 19 0 args [Ljava/lang/String;
public java.lang.Object run();
LineNumberTable:
line 1: 4
line 3: 9
line 5: 14
LocalVariableTable:
Start Length Slot Name Signature
0 63 0 this Ltest;
7 56 2 name Ljava/lang/Object;
12 51 3 surname Ljava/lang/String;
protected groovy.lang.MetaClass $getStaticMetaClass();
}
IDE syntax support
If you use IDE that supports Groovy well (e.g. IntelliJ IDEA) then you should be able to make usage of type inference and IDE would provide you a syntax support.
Purpose of def
keyword
The main purpose of def
is to introduce dynamic types in Groovy. As you can see in the above example, this is still old Java Object
type.
The good practice is to use static types whenever you use static type on purpose. Your public API should definitely use static types for documentation reasons. I personally use def
from time to time in two cases:
- in local variables that has very limited scope and variable name provides all information about the variable itself
- in Spock unit tests in test case name e.g.
def "should do something"() { }