Java Reference
In-Depth Information
One particularly interesting feature of collections is that they support type coercion using
the
as
operator. What does that mean? It's not terribly difficult to convert a Java list into a
set, because there's a constructor for that purpose. Converting a list into an array, however,
involves some awkward, counterintuitive code. Here's Groovy's take on the process:
def names = teams as String[]
assert names.class == String[]
def set = teams as Set
assert set.class == java.util.HashSet
plicates and doesn't guarantee order.
9
I know I say that a lot, but with Groovy I think it a lot, too.
The as operator
Groovy uses the keyword
as
for many purposes. One of them is type coercion, which con-
verts an instance of one class into an instance of another.
One of the nicest features of Groovy collections is that they're searchable. Groovy adds
both
find
and
findAll
methods to collections. The
find
method takes a closure and
returns the first element that satisfies the closure:
assert 'New Hampshire' ==
['New Hampshire','New Jersey','New York'].find { it =~
/
New
/
}
The
findAll
method returns all the elements that satisfy the closure. This example re-
turns all the cities that have the letter
e
in their name:
def withE = cities.findAll { city -> city =~
/
e
/
}
assert withE == ['Seattle', 'New York', 'Cleveland']
Groovy also supplies the methods
any
and
every
, which also take closures:
assert cities.any { it.size() < 7 }
assert cities.every { it.size() < 10 }