Learn Java for Web Development

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

Field Operator

Groovy provides a way to bypass the getter and access the underlying field directly. Bypassing the
getter and accessing the underlying field is not recommended, however, because it is a violation of
encapsulation. Listing B-39 shows an example of using the field operator (.@).


Listing B-39. Using the Field Operator


class Author {
String name
}
def author = new Author(name: "Vishal")
println author.name
println author.@name


Vishal


Vishal


In this example, the first println uses the getter to access name, and the second println bypasses
the getter to access name directly.


Method Closure Operator

The method closure operator (.&) allows the method to be accessed and passed around like a
closure (see Listing B-40).


Listing B-40. Using the Method Closure Operator


def list = ["A","B","C"]
list.each { println it }
String printName(String name) {
println name
}
list.each(this.&printName)


A B C A B C

Free download pdf