Search code examples
functiongroovyparametersdefault-value

Default value parameter in Groovy as middle argument


I have a simple question. Why I can ommit middle parameter in case below?

    def testMethod(arg1, arg2 = "arg2", arg3) {
    println arg1
    println arg2
    println arg3
}

def "testMethod"() {
    given:
    testMethod("arg1", "arg3")
}

Output:

enter image description here


Solution

  • In groovy you can assign default values to method's arguments, making those arguments optional.

    Usually the optional arguments are the trailing ones, and that makes sence from the POV of calling such methods.

    You could also declare default values for the middle arguments, like you did. In this case you should be aware of which arguments will get the defaults and which will not.

    Consider the extension of your example:

    def testMethod(arg1, arg2 = "arg2", arg3) {
        println arg1
        println arg2
        println arg3
    }
    testMethod 1, 3
    
    println '-----------'
    
    def testMethod1(arg1, arg2 = "arg2", arg3 = 'arg3') {
        println arg1
        println arg2
        println arg3
    }
    testMethod1 1,2
    

    It prints:

    1
    arg2
    3
    -----------
    1
    2
    arg3
    

    So, when calling both methods with 2 arguments, the testMethod replaces the 2nd arg with default, whereas the testMethod1 defaults the 3rd arg.