Groovy method with optional parameters

前端 未结 3 1309
清酒与你
清酒与你 2021-02-01 12:43

I would like to write a wrapper method for a webservice, the service accepts 2 mandatory and 3 optional parameters.

To have a shorter example, I would like to get the f

3条回答
  •  情歌与酒
    2021-02-01 13:05

    Can't be done as it stands... The code

    def myMethod(pParm1='1', pParm2='2'){
        println "${pParm1}${pParm2}"
    }
    

    Basically makes groovy create the following methods:

    Object myMethod( pParm1, pParm2 ) {
        println "$pParm1$pParm2"
    }
    
    Object myMethod( pParm1 ) {
        this.myMethod( pParm1, '2' )
    }
    
    Object myMethod() {
        this.myMethod( '1', '2' )
    }
    

    One alternative would be to have an optional Map as the first param:

    def myMethod( Map map = [:], String mandatory1, String mandatory2 ){
        println "${mandatory1} ${mandatory2} ${map.parm1 ?: '1'} ${map.parm2 ?: '2'}"
    }
    
    myMethod( 'a', 'b' )                // prints 'a b 1 2'
    myMethod( 'a', 'b', parm1:'value' ) // prints 'a b value 2'
    myMethod( 'a', 'b', parm2:'2nd')    // prints 'a b 1 2nd'
    

    Obviously, documenting this so other people know what goes in the magical map and what the defaults are is left to the reader ;-)

提交回复
热议问题