Ant's
Ant's

Reputation: 13811

What does this Groovy code do?

I got this program from GroovyConsole. I'm reproducing here for easy reference,

def aClosure = { String name ->

println "hi "+name
sayHello()
println wro4j

}

aClosure.delegate = new MyClass()
aClosure.resolveStrategy = Closure.DELEGATE_FIRST

def result = aClosure("Toto")

class MyClass{

String wro4j = "Wro4J rocks !!!"

void sayHello(){
println "Hello"
}

}

I couldn't figure out what the above code does.

Whats are resolveStrategy and delegate with respect to aClousre?

Upvotes: 1

Views: 141

Answers (1)

Alex Objelean
Alex Objelean

Reputation: 4133

The delegate of the closure is the class which methods will be invoked from within the closure. In other words, when sayHello() method is invoked, groovy performs a lookup of this method from within the MyClass.

Regarding the strategy: DELEGATE_FIRST. With this resolveStrategy set the closure will attempt to resolve property references to the delegate first.

These are descriptions of all strategies from http://groovy.codehaus.org/api/groovy/lang/Closure.html:

Upvotes: 3

Related Questions