groovy对可选参数的调用

groovy对可选参数的调用,groovy,Groovy,我有一个方法如下: void display(def a = null, def b = null) { // user provides either value for a, or b // if he gives value for a, it will be used // if he gives value for b, it will be used // not supposed to provide values for both a and b } 我的问题是,用户

我有一个方法如下:

void display(def a = null, def b = null) {

// user provides either value for a, or b
// if he gives value for a, it will be used 
// if he gives value for b, it will be used 

// not supposed to provide values for both a and b

}
我的问题是,用户应该如何为b提供值

如果我使用

display(b = 20)
它将20分配给
a
,这是我不想要的

要做到这一点,唯一的方法是按如下方式调用

display(null, 20) 

对于可选参数,是的,您必须调用
display(null,20)
。但您也可以定义方法来接受映射

void display(Map params) {
    if(params.a && params.b) throw new Exception("A helpful message goes here.")

    if(params.a) { // use a }
    else if(params.b) { // use b }
}
然后可以这样调用该方法:

display(a: 'some value')
display(b: 'some other value')
display(a: 'some value', b: 'some other value') // This one throws an exception.

对于可选参数,是的,您必须调用
display(null,20)
。但您也可以定义方法来接受映射

void display(Map params) {
    if(params.a && params.b) throw new Exception("A helpful message goes here.")

    if(params.a) { // use a }
    else if(params.b) { // use b }
}
然后可以这样调用该方法:

display(a: 'some value')
display(b: 'some other value')
display(a: 'some value', b: 'some other value') // This one throws an exception.

可能的复制品可能的复制品就是我要找的!!这对于我在项目中遇到的实际问题来说非常有意义!非常感谢@Emmanuel Rosa!这就是我要找的!!这对于我在项目中遇到的实际问题来说非常有意义!非常感谢@Emmanuel Rosa!