Database Reference
In-Depth Information
•  findAll: gather all of the elements of the collection that make a closure return a
value of true, and return them in a new collection
•  [1, 2, 3, 4].findAll{ it > 2 } // returns [3, 4], all values that are > 2
•  every: Execute a closure against every element of the collection and return a
true if the closure returns a true every time[1, 2, 3, 4].every{ it > 2 } // returns
false (some values are <= 2)
•  any: Execute a closure against elements of the collection, and check if any one of
them is found that makes the closure return a true
•  [1, 2, 3, 4].any{ it > 2 } // returns true (at least one value is > 2)
These methods, enabled by closures, are found throughout groovy code and are
prime contributors to the expressiveness, power, and readability the language offers.
9.4.7 Everything Is an Object
In groovy, every value, every variable, every parameter, every everything is an object.
This contrasts with Java where some things are objects (reference types) and some are
simply values (primitive types). With only one kind of thing available, we do not have
to spend any energy thinking about which thing is which. We are free to think of every-
thing the same way. This leads to some very interesting constructions like calling meth-
ods on integers.
3.times{ println 'Location! ' } // prints Location! Location!
Location!
2.step(10, 2) { println it + ' is even' } // steps from 2 to 10
(exclusive) by 2s
cutoffDate = 6.months.ago // creates a Date object using today's
date, minus 6 months
The important thing to remember about this feature is that groovy handles all
conversions automatically. The source code may appear to have primitive types, but
they are always created as objects when the code runs. When groovy has to inter-
act with Java objects, quite often those objects expect to receive primitive types as
parameters. The change happens automatically. Primitives go out where needed, and
primitives coming in from Java are immediately changed into objects. This is called
automatic “boxing” and “unboxing.” In effect, it means there is no need for us to
think about it.
9.4.8 Automatic Getters and Setters
As mentioned in a sidebar in Section 9.3.3, groovy looks through objects as they are
created, finds methods that match certain patterns, and automatically sets up access to
them through a property-like syntax. The reverse is also true. groovy makes creating
custom classes much easier by automatically creating “getter” and “setter” functions.
The following code calls these methods in both ways.
class EssDB {
String name
// class fields, for which automatic
String application
// getters and setters are created
}
db = new EssDB()
Search WWH ::




Custom Search