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 = 1000This code will not throw Exception. The code above is similar to the one below:
Object myvar = 'Test' myvar = 1000As previously stated, using def is like declaring the variable to have the type Object.
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 WorldThe 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) } }