Java Reference
In-Depth Information
public
String getName() {
return
"from getter: " + name;
}
Now I have to modify each of the asserts to include the string "
from getter:
" for them
to still return true.
The third person,
willow
, is constructed using the
as
operator in Groovy. This operator
has several uses, one of which is to coerce a map into an object as shown here. In this case
the operator instantiates a person and supplies the map as properties for the resulting in-
stance.
Moving on, I can also add the person instances to a Groovy collection, which isn't all that
surprising but has some nice additional benefits. For example, Groovy collections support
operator overloading, making it easy to add additional persons and have additional meth-
ods for searching:
def slayers = [buffy, faith]
assert ['Buffy','Faith'] == slayers*.name
assert slayers.class == java.util.ArrayList
def characters = slayers + willow
assert ['Buffy','Faith','Willow'] == characters*.name
def doubles = characters.findAll { it.name =~ /
([a-z])\1
/ }
assert ['Buffy','Willow'] == doubles*.name
Groovy has a native syntax for collections, which simplifies Java code. Putting the referen-
ces inside square brackets creates an instance of the
java.util.ArrayList
class and
adds each element to the collection. Then, in the
assert
statement, I used the so-called
“spread-dot” operator to extract the
name
property from each instance and return a list of
the results (in other words, the spread-dot operator behaves the same way
collect
does).
By the way, I restored the
getName
method to its original form, which returns just the
attribute value.
I was able to use operator overloading to add
willow
to the
slayers
collection, result-
inginthe
characters
collection. Finally,Itookadvantage ofthe fact that inGroovy,the
java.util.Collection
interface has been augmented to have a
findAll
method
that returns all instances in the collection matching the condition in the provided closure.