coderatchet
coderatchet

Reputation: 8428

apply closure to an arbitrary object in groovy

In gradle there are places where you can pass a closure to an object itself in a builder style like so:

// ant is a property. an object.
ant {
    // do funky builder stuff
}

How can you create your own custom code to apply closures to objects? is there a method that i need to override in order to support this?

Upvotes: 2

Views: 1663

Answers (3)

Kurt
Kurt

Reputation: 535

Take a look at:

Object.tap {} 
Object.with {}

Upvotes: 0

kdabir
kdabir

Reputation: 9868

Adding to the way seagull mentioned:

Using a method that takes a closure:

class MyClass { 
  def ant (c) {
    c.call()
  }
}

def m = new MyClass()
m.ant { 
  println "hello"
}

Other one, using method missing, which gives more flexibility in terms of name of the method that takes a closure (ant in your case):

class A {
     def methodMissing(String name, args) {
        if (name == "ant") {
            // do somehting with closure
            args.first().call()
        }
    }
}

def a = new A()

a.ant { println "hello"}

Upvotes: 3

Seagull
Seagull

Reputation: 13859

You could override the call operator. Groovy allows you to not place round braces around the closure argument.

class A {
  def call(Closure cl) {
    print(cl())
  }
}
def a = new A();
a {
    "hello"
}

Prints hello.

Upvotes: 3

Related Questions