Ramesh KP
Ramesh KP

Reputation: 35

Groovy closure DELEGATE_ONLY and DELEGATE_FIRST strategy not working

I have the following code snippet in my Demo.groovy file

class Person {
    String name
}
def name='no name'
def p = new Person(name:'Igor')
def cl = { name.toUpperCase() }
cl.resolveStrategy = Closure.DELEGATE_ONLY
cl.delegate = p
println cl()

According to the Groovy Documentation on closure strategy http://groovy-lang.org/closures.html

I expect the following output

IGOR

However the code seems to print

NO NAME

Can anybody help me understand why does groovy print NO NAME instead of IGOR with resolve strategy set to DELEGATE_ONLY?

Upvotes: 2

Views: 1111

Answers (2)

RanjaniH
RanjaniH

Reputation: 1

This ISNT a very clean example to demonstrate delegation. In order for delegation to occur correctly we need to have one owner and another delegate. Refer this for better understanding:

def cl = {
    append 'Groovy'
    append 'DSL'
}

String append(String s) {
    println "appending $s"
}

StringBuffer sb = new StringBuffer()
cl.resolveStrategy = Closure.DELEGATE_ONLY
cl.delegate = sb
println(cl.delegate.class)
println cl()​

Here when DELEGATE_ONLY is applied the append() of StringBuffer is called, else the append method declared in the script is called.

Upvotes: 0

Marmite Bomber
Marmite Bomber

Reputation: 21063

The documentation says:

Whenever, in a closure, a property is accessed without explicitly setting a receiver object, then a delegation strategy is involved

This is not the case in your example, where the variable nameis defined. Remove it, or move it after the definition of the closere and you'll see the expected result

class Person {
    String name
}
def p = new Person(name:'Igor')
def cl = { name.toUpperCase() }
def name='no name'
cl.resolveStrategy = Closure.DELEGATE_ONLY

cl.delegate = p
println cl()

IGOR

Upvotes: 2

Related Questions