闭包中的默认参数

时间:2016-10-28 15:16:36

标签: groovy closures

查看groovy manual,我发现我应该能够在闭包中使用默认参数,如下所示:

def closureWithTwoArgAndDefaultValue = { int a, int b=2 -> a+b }
assert closureWithTwoArgAndDefaultValue(1) == 3

但是,在groovysh中运行该错误会产生以下错误:

  

错误groovy.lang.MissingMethodException:   没有方法签名:groovysh_evaluate.closureWithTwoArgAndDefaultValue()适用于参数类型:(java.lang.Integer)值:[1]

有人可以告诉我为什么吗?

1 个答案:

答案 0 :(得分:0)

尝试省略def

closureWithTwoArgAndDefaultValue = { int a, int b=2 -> a+b }
assert closureWithTwoArgAndDefaultValue(1) == 3

有关详细说明,请参阅here