JonesV JonesV - 1 month ago 23
Groovy Question

Default parameter in closure

Looking at the groovy manual, I see that I should be able to use default parameters in closures, like so:

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


However, running that in
groovysh
gives me the following error:


ERROR groovy.lang.MissingMethodException:
No signature of method: groovysh_evaluate.closureWithTwoArgAndDefaultValue() is applicable for argument types: (java.lang.Integer) values: [1]


Could somebody tell me why?

Answer

Try to omit def:

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

For further explanation, see here.