Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 38 ยท Collections and Closures

Closure Delegate, Currying and Composition

Go deeper with Groovy closures: this, owner and delegate, resolve strategies, currying and partial application, composition with << and >>, memoize and trampoline.

You now know how to write and call closures. This lesson explains what makes Groovy closures special: the three objects a closure can talk to (this, owner, delegate), how changing the delegate lets code configure other objects (the trick behind builders and Gradle), and how to build new closures from old ones with currying, composition, memoization and trampolines.

Groovy code is read-only on this site. Java stand-ins show the same functional ideas with runnable code.

this, owner and delegate

Inside a closure, three special references exist:

Name Meaning
this The enclosing class instance (or script) where the closure is written
owner The object that directly contains the closure: the enclosing class, or another closure if nested
delegate An object you can change; by default it equals the owner
GROOVY
class Demo {
    def run() {
        def c = { [this.class.name, owner.class.name, delegate.class.name] }
        println c()
        def nested = { def inner = { owner.class.name }; inner() }
        println nested()          // the owner of inner is the outer closure
    }
}
new Demo().run()

For the outer closure c, all three point to the Demo instance. For inner, owner is the outer closure (its class name is something like Demo$_run_closure2, an implementation detail) while this is still the Demo.

Changing the delegate

When a closure calls a name it does not define itself, Groovy looks for it first in the owner, then the delegate. You can set the delegate to point at any object:

GROOVY
class Greeter {
    String name
    String hello() { "Hello, $name" }
}

def code = { hello() }
code.delegate = new Greeter(name: 'Ada')
println code()           // Hello, Ada

The method hello() is not defined anywhere around the closure, so Groovy asks the delegate. This is a form of late binding: the closure is written once and bound to different objects later.

Resolve strategies

resolveStrategy decides which object is asked first:

Strategy Lookup order
Closure.OWNER_FIRST (default) owner, then delegate
Closure.DELEGATE_FIRST delegate, then owner
Closure.OWNER_ONLY owner only
Closure.DELEGATE_ONLY delegate only
Closure.TO_SELF the closure itself
GROOVY
class Config {
    String host = 'localhost'
    int port = 80
}

def configure(Closure body) {
    def cfg = new Config()
    body.resolveStrategy = Closure.DELEGATE_FIRST
    body.delegate = cfg
    body()
    cfg
}

def result = configure {
    host = 'example.org'      // assigns cfg.host
    port = 8080               // assigns cfg.port
}
println "$result.host:$result.port"     // example.org:8080

This pattern, delegate = target with DELEGATE_FIRST, is the heart of every Groovy DSL. The closure body looks like a configuration file, but it is ordinary code run against a configuration object. Gradle's dependencies { ... } blocks work this way.

The Java stand-in below imitates the idea with a configurator that receives the target object explicitly, since Java has no delegate concept.

Java Java stand-in: a configure(block) helper

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

You will use delegates heavily when the course reaches builders and DSLs.

Currying

Currying turns a closure with several parameters into one that remembers some of them. curry fixes arguments from the left:

GROOVY
def volume = { h, w, l -> h * w * l }
def tall = volume.curry(10)          // h fixed to 10
println tall(2, 3)                   // 60

def log = { String level, String msg -> "[$level] $msg" }
def warn = log.curry('WARN')
println warn('disk almost full')     // [WARN] disk almost full
  • curry(a) fixes the first parameter(s).
  • rcurry(z) fixes the last parameter(s).
  • ncurry(index, value) fixes a parameter at a position.
GROOVY
def power = { base, exp -> base ** exp }
def squareOf = power.rcurry(2)
println squareOf(9)                  // 81

Currying is partial application: you build specialised functions from a general one without writing new code.

Java Java stand-in: partial application

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Composition

Two operators chain closures:

  • f >> g means "run f, then pass its result to g" (left to right).
  • f << g means "run g first, then pass its result to f" (like math f(g(x))).
GROOVY
def inc = { it + 1 }
def dbl = { it * 2 }
def incThenDbl = inc >> dbl
def dblThenInc = inc << dbl
println incThenDbl(5)        // 12  ((5 + 1) * 2)
println dblThenInc(5)        // 11  (5 * 2 + 1)

def trim = { String s -> s.trim() }
def upper = { String s -> s.toUpperCase() }
def pipeline = trim >> upper
println pipeline('  hello ')   // HELLO

Composition lets you describe a data pipeline as a value: build it once, reuse it, test its parts.

Memoization

memoize() returns a closure that caches results by argument, which is a one-line cache for pure, expensive functions:

GROOVY
def slowSquare = { n -> sleep 100; n * n }
def fast = slowSquare.memoize()
fast(12)     // slow the first time
fast(12)     // instant: result is cached

Variants limit the cache: memoizeAtMost(100), memoizeAtLeast(10), memoizeBetween(10, 100). Only use it for functions whose result depends solely on their arguments.

Trampolining deep recursion

A recursive closure that nests thousands of calls can overflow the stack. trampoline() turns the recursion into a loop:

GROOVY
def countDown
countDown = { n, acc ->
    n == 0 ? acc : countDown.trampoline(n - 1, acc + n)
}
countDown = countDown.trampoline()
println countDown(5, [])     // [5, 4, 3, 2, 1]

The trick is that the recursive call returns a "bounce" object instead of calling deeper, and the trampoline loop evaluates it step by step. Use it for tail-recursive algorithms (the recursive call is the last thing done).

The Closure as a decision aid

Closures can express decisions as data, for example validation rules:

GROOVY
def rules = [
    'not blank': { it?.trim() },
    'max 10 chars': { it.length() <= 10 }
]
def failed = rules.findAll { name, check -> !check('a very long input') }
println failed.keySet()      // [max 10 chars]

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the delegate of a closure by default?

    By default the delegate equals the owner. You can reassign it to any object.
  2. 2. Which resolve strategy makes unqualified names look at the delegate first?

    DELEGATE_FIRST asks the delegate first, then the owner. It is the usual choice for DSLs.
  3. 3. Given def add = { a, b -> a + b }, what does add.curry(5)(3) return?

    curry(5) fixes a to 5, so calling the result with 3 evaluates 5 + 3.
  4. 4. What does (f >> g)(x) compute?

    >> runs f first and then passes its result to g. << is the reverse order.
  5. 5. When is memoize() appropriate?

    Caching is only safe when the same arguments always give the same result.

Summary

  • this, owner and delegate determine where a closure looks up names; the delegate can be reassigned.
  • delegate with DELEGATE_FIRST is the engine of Groovy DSLs and builders.
  • curry, rcurry and ncurry fix parameters; >> and << compose closures.
  • memoize caches results and trampoline makes deep tail recursion safe.

Next: Collection Methods in Depth