Java Reference
In-Depth Information
and Dave Klein (lead author of Grails: A Quick-Start Guide ). Dierk had the best recom-
mendation I've ever heard on the subject. He said, “If I think of a type, I type it (pun inten-
ded).”
My own experience is that as I get more experienced with Groovy, I tend to use def less
and less. I agree with Dierk's recommendation, with the added advice that now when I de-
clare a type, I pause for a moment to see if any actual type occurs to me. If so, I use it.
In some cases def is preferred, most notably when using mock objects in testing. That
subject is discussed in chapter 6 .
Moving on to data types themselves, Java makes a distinction between primitives and
classes. In Groovy there are no primitives. Numbers in Groovy are first-class objects, with
their own set of methods.
B.2.1. Numbers
Because in Groovy numbers are objects, I can determine their data types. For integer liter-
als, the data type depends on the value, as shown in this script:
x = 1
assert x.class == java.lang.Integer
x = 10000000000000000
assert x.class == java.lang.Long
x = 100000000000000000000000
assert x.class == java.math.BigInteger
There are a few points to be made about this script. First, the variable x doesn't have a de-
claration at all. This is only legal in a script, where the variable becomes part of the script's
binding and can be set and accessed from outside. Details of this procedure are shown in
chapter 3 on integration with Java. Suffice it to say here that this is legal in a script, but not
in a class. If it makes you feel more comfortable, you're free to add the word def in front
of x.
Script Variables
If a variable in a script is not declared, it becomes part of the script's binding.
Search WWH ::




Custom Search