def and static types
A Groovy variable is either untyped or typed. def means Object with no check at compile time: the value can be a string now and a number later, and each call is resolved with the type the value has at that moment. A declared type checks the assignment and nothing else.
A variable with def
def.groovy
def value = 'text'
println value.toUpperCase()
value = 42
println value + 1
println value.getClass().name
groovy def.groovy
TEXT
43
java.lang.Integer
The second assignment is legal because def did not promise a string. The last line shows what the variable holds after it: an Integer, which is a Java class like any other.
A declared type
types.groovy
String name = 'Groovy'
int count = 3
List<String> names = ['Ada', 'Grace', 'Barbara']
println name
println count * 2
println names.join(', ')
println names.getClass().name
groovy types.groovy
Groovy
6
Ada, Grace, Barbara
java.util.ArrayList
A declared type buys a check at compile time and a reader who does not have to guess. The generic parameter of List<String> is a promise to the reader and to a static checker; the JVM erases it, which is why the last line names the plain class.
The @CompileStatic lesson makes the compiler enforce those promises.
Which method is called
With two overloads, Groovy picks the most specific one for the value it has. A String reaches the String overload and an Integer the Object one:
dispatch.groovy
String describe(Object value) {
"object: ${value}"
}
String describe(String value) {
"string: ${value}"
}
println describe('text')
println describe(42)
groovy dispatch.groovy
string: text
object: 42
That is dynamic dispatch: the call is resolved when it runs, with the runtime type. Java decides at compile time from the declared type, and the Java course shows the other side of the same rule.
Related
- Strings and GStrings: the type the first example used.
- @CompileStatic and @TypeChecked: when the compiler takes the checks back.
Article author: Arthur Isaev