4.9 Closure Delegation

Closures in Groovy go far beyond being simple anonymous methods; they have some powerful capabilities, as we’ll see in the rest of this chapter. Groovy closures support method delegation, and provide capabilities for method-dispatching—much like JavaScript’s support for prototypal inheritance. Let’s understand the magic behind this and how to put this to good use.

Three properties of a closure—​this​, ​owner​, and ​delegate​—determine which object handles a method call from within a closure. Generally, the ​delegate​ is set to ​owner​, but changing it lets us exploit Groovy for some really good metaprogramming capabilities. Let’s examine these properties for closures:

UsingClosures/ThisOwnerDelegate.groovy
 
def​ examiningClosure(closure) ...

Get Programming Groovy 2 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.