简体   繁体   中英

Default Value for Closure Parameters in Groovy

Is there some way to use default parameters values with closures in Groovy?

This is what I tried so far:

class Persona {
    String name

    Persona( String name ) {
        this.name = name
    }

    String salute( String salute = "Hola" ) {
        salute + ' ' + this.name
    }

}

Persona.metaClass.salute2 = { 
    String salute = "Hola" ->
        salute + ' ' + name
}

p = new Persona( 'john' )

print p.salute()
print p.salute2()

which gives me the following result:

Hola johnnull john

It seems like the call to salute2() is ignoring the salute default value "Hola" .

您的代码可以按预期的那样与Groovy 1.6-RC2一起正常工作。

I don't believe Groovy has a direct way to do what you're asking.

The way to simulate this is for "salute2" to be a closure that defines another closure inside it (the one that currently concatenates the "salute" and "name" variables, where "salute" is a closure parameter)), and then calls that closure, sending the value "Hola".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM