Method pointers

Groovy allows you to assign a method to a closure by using the & syntax. The closure returned is often referred to as a method pointer. Method pointers can be assigned by dereferencing the method name from any object instance, for example:

given:
def list = ["A", "B", "C"]

when:
def addToList = list.&add

and:
addToList "D"

then:
list ==  ["A", "B", "C", "D"]

The difficulty with method pointers to instance methods is being sure what instance the method pointer is referencing. In essence, an instance method pointer violates the encapsulation rules for the object by passing control to an object that is outside the direct control of a class. So I recommend caution when using them. However, method pointers when applied to static methods ...

Get Groovy for Domain-specific Languages - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.