how to pass parameters to the closure if use @DelegatesTo annotation?

726 Views Asked by At

if i change the code in Groovy DSL Doc here.

add some string 'hello world' to email, like this

email('hello world') { // change here
   from '[email protected]'
   to '[email protected]'
   subject 'The pope has resigned!'
   body {
      p 'Really, the pope has resigned!'
   }
}

and change

def email(def name, @DelegatesTo(EmailSpec) Closure cl) {  // change here
    def email = new EmailSpec()
    def code = cl.rehydrate(email, this, this)
    code.resolveStrategy = Closure.DELEGATE_ONLY
    code.call(name) // change here
}

so, how to modify the class EmailSpec to get the string 'hello world' ??

2

There are 2 best solutions below

0
On

Yes, i found a way, but not perfect.

Simple

new EmailSpec(name)  // change to 

however, i really want to use groovy function call(name) to solve it

0
On

To tell the compile that the closure will be called with a parameter you need to add the ClosureParams annotation.

To stick with your example:

def email(def name,
        @ClosureParams(value = SimpleType, options = "java.lang.String")
        @DelegatesTo(EmailSpec) Closure cl) {
    def email = new EmailSpec()
    def code = cl.rehydrate(email, this, this)
    code.resolveStrategy = Closure.DELEGATE_ONLY
    code.call(name) // change here
}

will tell the compiler that the first parameter is a String.

For more details have a look at the section The @ClosureParams annotation in the groovy documentation.