Book Image

Groovy for Domain-Specific Languages, Second Edition

By : Fergal Dearle
Book Image

Groovy for Domain-Specific Languages, Second Edition

By: Fergal Dearle

Overview of this book

Table of Contents (20 chapters)
Groovy for Domain-specific Languages Second Edition
About the Author
About the Reviewers
Free Chapter
Introduction to DSLs and Groovy

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:

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

def addToList = list.&add

addToList "D"

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 can be a very useful way to create DSL shortcut keywords.