Java Reference
In-Depth Information
In Groovy you create a map with square brackets, and each entry consists of keys and
values separated by a colon. The keys are assumed to be strings by default. The values
can be anything. By default, the params variable is an instance of java.util
.LinkedHashMap .
Collections
Groovy has native syntax for lists and maps. Map keys are assumed to be strings.
Each corresponding value is surrounded by single quotes. In Groovy, single-quoted strings
are instances of java.lang.String . Double-quoted strings are “interpolated” strings,
known (unfortunately) as GString s. I'll show an example of string interpolation later in
this program.
To transform the map into a query string I first need to convert each of the map entries into
strings of the form “key=value,” and then I need to concatenate them all together using am-
persands as separators. [ 2 ] The first step is accomplished by using a special method added to
all Groovy collections, known as collect . The collect method takes a closure as an
argument, applies the closure to each element of the collection, and returns a new collec-
tion containing the results.
2 I also need to URL-encode the map entries, but in this case they're already fine. In other examples of RESTful web
services I'll demonstrate the encoding process.
Closures are introduced in the next sidebar and discussed extensively throughout the topic,
but for the moment think of them as blocks of code representing the body of a function,
which may take dummy arguments. In the case of collect , when applied to a map, the
closure can take either one or two arguments. If the closure takes one argument, the argu-
ment represents a Map.Entry ; with two arguments, the first is the key and the second is
the value for each entry.
To transform the map into a list of key=value pairs, the following two-argument closure
works in the collect method:
params.collect { k,v -> "$k=$v" }
 
Search WWH ::




Custom Search