Grails Cookbook - A collection of tutorials and examples

Groovy Def Declaration Examples

When we declare a variable or function in Groovy, we can use the def keyword to define the type. The Groovy Def can be used if we don't want to restrict the type of an object. Hence, we can change what can be assigned to a variable any time during runtime. When we use Groovy def to declare something, it is similar to declaring it as an Object class. Because the class Object is the root class of all classes, you can assign anything to a variable of type Object. Here are some examples on how to use def in Groovy.

Groovy Def Variables

We can NOT do this in Java or Groovy.
String myvar = 'Test'
myvar = 1000

This will throw a Runtime Exception because the code is trying to assign an integer to a String variable.

We can use def to declare the type of a variable. And we can assign anything to it.

def myvar = 'Test'
myvar = 1000
This code will not throw Exception. The code above is similar to the one below:
Object myvar = 'Test'
myvar = 1000
As previously stated, using def is like declaring the variable to have the type Object.

Groovy Def Function/Method

We can also use the def keyword to define the return of a function or method. Consider the code below where the return type of a method is declared as int.
class DefExample {
   public static int foo(int i) {
      if ( i < 100 ) {
         return -1
      }
      return 'Hello World'
   }
   static void main(String[] args) {
      println foo(50)
      println foo(200)
   }
}

Here is the output of the code. As seen, the code will throw an Exception. This is because the second line will try to return a String when the method is expected to return an int.

-1
Caught: org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object 'Hello World' with class 'java.lang.String' to class 'int'
org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object 'Hello World' with class 'java.lang.String' to class 'int'
	at DefExample.foo(DefExample.groovy:6)
	at DefExample.main(DefExample.groovy:10)

When we declare the return type as def, it means the method can return any type of object.

class DefExample {
   public static def foo(int i) {
      if ( i < 100 ) {
         return -1
      }
      return 'Hello World'
   }
   static void main(String[] args) {
      println foo(50)
      println foo(200)
   }
}
The output of the modified code is below. Notice that the exception is now gone.
-1
Hello World
The code is similar to below. That is, a method declared as def is like declaring it to return an Object type.
class DefExample {
   public static Object foo(int i) {
      if ( i < 100 ) {
         return -1
      }
      return 'Hello World'
   }
   static void main(String[] args) {
      println foo(50)
      println foo(200)
   }
}