Ranges
Ranges appear inclusively like 0..10 or half-exclusively like 0..<10. They are often enclosed in parentheses since the range operator has low precedence.
Integer ranges are often used for selecting sublists. Range boundaries can be of any type that defines previous(), next() and implements Comparable. Notable examples are String and Date.
Lists
Lists look like arrays but are of type java.util.List plus new methods.
The sort() method is often used and comes in three flavors:
Sort call |
Usage |
col.sort() |
natural sort for comparable objects |
col.sort { it.propname } |
applying the closure to each item before comparing the results |
col.sort { a,b -> a <=> b } |
closure defines a comparator for each comparison |
Lists can also be indexed with negative indexes and reversed ranges.
Sublist assignments can make a list grow or shrink and lists can contain varying data types.
Maps
Maps are like lists that have an arbitrary type of key instead of integer. Therefore, the syntax is very much aligned.
Maps can be accessed in a conventional square-bracket syntax or as if the key was a property of the map.
There is also an explicit get method that optionally takes a default value.
Map iteration methods take the nature of Map.Entry objects into account.
GPath
Calling a property on a list returns a list of the property for each item in the list.
returns a list of town objects.
To do the same with method calls, use the spread-dot operator.
Closures
Closures capture a piece of logic and the enclosing scope. They are first-class objects and can receive messages, can be returned from method calls, stored in fields, and used as arguments to a method call.
Use in method parameter
Use as last method argument
Construct and assign to local variable
Bind leftmost closure param to fixed argument
Closure parameter list examples:
Closure.isCase(b) sends b to the closure and returns the call result as boolean. Use as in