代码之家  ›  专栏  ›  技术社区  ›  opensas

Groovy中闭包参数的默认值

  •  0
  • opensas  · 技术社区  · 17 年前

    这是我迄今为止所尝试的:

    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()
    

    这给了我以下结果:

    Hola johnnull john
    

    这似乎是对 salute2() 忽略礼炮默认值 "Hola" .

    2 回复  |  直到 17 年前
        1
  •  2
  •   chanwit    17 年前

    您的代码在Groovy 1.6-RC2中运行良好,正如您所期望的那样。

        2
  •  -1
  •   David M. Karr    17 年前

    我不相信Groovy有直接的方法来完成你的要求。