使用可选参数的Groovy方法 [英] Groovy method with optional parameters

查看:129
本文介绍了使用可选参数的Groovy方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为webservice编写一个包装方法,该服务接受2个必需参数和3个可选参数。

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 following code working

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

myMethod();
myMethod('a')
myMethod(pParm2:'a') // doesn't work as expected
myMethod('b','c')

输出结果为:

The output is:

12
a2
[pParm2:a]2
a2
bc

我想实现的是给出一个参数,并得到 1a 作为结果。
这是可能的(以最懒惰的方式)吗?

What I would like to achieve is to give one parameter and get 1a as the result. Is this possible (in the laziest way)?

推荐答案

代码

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

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

基本上可以使groovy创建以下方法: / p>

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' )
}

另一种方法是将可选Map作为第一个参数:

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 ;-)

这篇关于使用可选参数的Groovy方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆