Groovy method with optional parameters

前端 未结 3 1351
清酒与你
清酒与你 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 12:50

    Just a simplification of the Tim's answer. The groovy way to do it is using a map, as already suggested, but then let's put the mandatory parameters also in the map. This will look like this:

    def someMethod(def args) {
        println "MANDATORY1=${args.mandatory1}"
        println "MANDATORY2=${args.mandatory2}"
        println "OPTIONAL1=${args?.optional1}"
        println "OPTIONAL2=${args?.optional2}"
    }
    
    someMethod mandatory1:1, mandatory2:2, optional1:3
    

    with the output:

    MANDATORY1=1
    MANDATORY2=2
    OPTIONAL1=3
    OPTIONAL2=null
    

    This looks nicer and the advantage of this is that you can change the order of the parameters as you like.

提交回复
热议问题