【问题标题】:groovy call for optional parameters对可选参数的常规调用
【发布时间】:2015-10-28 00:23:52
【问题描述】:

我有一个方法如下:

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) 

【问题讨论】:

标签: groovy


【解决方案1】:

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

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!
猜你喜欢
  • 1970-01-01
  • 2011-02-22
  • 1970-01-01
  • 2011-10-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-04
  • 1970-01-01
相关资源
最近更新 更多