Database Reference
In-Depth Information
9.4.3 Dynamic Typing
groovy, along with most scripting languages, is in the large family of languages that are
known as dynamically typed. The definition of the term is somewhat complex, and not
everyone agrees on it, so we will focus on the most important aspect of its meaning to
us. Dynamic typing means that we do not have to declare the type of every variable in
our source code. In groovy, we do not have to type int i; to declare the variable i. We can
type def i and later assign a value of any type to it without worrying that the compiler
will complain. In scripts, we do not even have to use the keyword def. We can just assign
a value to a new variable and keep on moving. We also can leave out type declarations
from the parameters in function and closure definitions.
The sample code in this chapter takes advantage of these options extensively. They are
very helpful when writing simple programs that can be understood at a glance, when
objects are very short-lived, or when declaring their types does not really add any addi-
tional meaning to the program. The more complex a program is, and the more it does
with a given object, the more static typing (explicitly declaring the types of variables
and parameters) is called for. It is also very useful when working in an integrated devel-
opment environment (IDE), such as IntelliJ IDEA, to use static typing more often, as
the IDE is better able to do code-completion assistance and other magic tricks. Finally,
static typing allows the compiler to catch some type compatibility errors that otherwise
would only be caught at runtime. ultimately, the individual developer will find the right
mix of dynamic and static typing that works best. The important thing to us is that the
choice is available.
9.4.4 Closures
groovy features the ability to define blocks of code that can be thought of as living
pieces of the program: as functions and as data. They are called closures. A closure can
be assigned as a value to a variable and then called through the variable name. Closures
can also be passed as parameters to methods, either in the form of variables or as closure
literals defined in place. The following snippet does the same thing in two equivalent
ways (recall that the name 'it' is the default name given to the parameter when a closure
only has one):
//method one
testArr = [1, 3, 5, 7, 4, 2, 3, 8, 5]
println testArr.findAll{ it % 2 == 0 } //mod operator (the
remainder after dividing)
//method two
isEven = {
if ( it % 2 == 0 ) {
return true
} else {
return false
}
}
println testArr.findAll{ isEven(it) }
The result is that [4, 2, 8] is printed both times. It is very common to use closures
defined in place with iterator methods like the findAll we see in line three above, but
Search WWH ::




Custom Search