Tuesday, September 9, 2008

How to define a closure by method

 To declaring a closure is to reuse something that is already declared: a method. Methods have a body, optionally return values, can take parameters, and can be called. The similarities with closures are obvious, so Groovy lets you reuse the code you already have in methods, but as a closure. Referencing a method as a closure is performed using the reference.& operator. The
reference is used to specify which instance should be used when the closure is called, just like a normal method call to reference.someMethod().
for example:
class TestClass{
   hello(String name){
     println("Hello ${name}")
 }
}
def tc=new TestClass()
def testClosure=tc.&hello //now you obtained a new closure by class method.

No comments: