Learn Java for Web Development

(Tina Meador) #1
APPENDIX B: Introduction to Groovy 419

Passing a Closure as a Parameter

A closure is an object. You can pass closures around just like any other objects. A common example
is iterating over a collection using a closure (see Listing B-34).


Listing B-34. Passing a Closure As a Parameter


def list = ["A", "B", "C"]
def x = { println it }
list.each(x)


A


B


C


Specialized Operators


Groovy includes several standard operators found in other programming languages, as well as
operators that are specific to Groovy that make it so powerful. In the sections that follow, you will
learn the specialized operators in Groovy such as spread, Elvis, safe navigation, field, method
closure, and diamond operators.


Spread Operator

The spread operator (*.) is a shorthand technique for invoking a method or closure on a collection of
objects. Listing B-35 illustrates the usage of the spread operator for iterating over a list.


Listing B-35. Using the Spread Operator



  1. def map = [1:"A", 2:"B", 3:"C", 4:"D"]

  2. def keys = [1, 2, 3, 4]

  3. def values = ["A", "B", "C", "D"]

  4. assert map*.key == keys

  5. assert map*.value == values


Line 4 and line 5 use the spread operator to access keys and values of the map.


Elvis Operator

The Elvis operator (?:) is a shorthand version of the Java ternary operator. For example, b= a ?: 1
could be interpreted as follows:


if(a != 0)
b = a
else
b = 1

Free download pdf