使用 documented mixture of named and positional arguments (或具有默认值的 args),如何在不指定任何命名参数的情况下调用方法?
我试图在不破坏其他人的代码的情况下扩展现有的共享方法,这种方法看起来很有希望,但下面的例子失败了:
def test(Map args, some, thing='default value'){
"$some $thing";
}
//good - adding any named parameter works
//test('yet', 'another good', anything:'notneeded');
//but not specifying named parameter fails
test('this', 'fails');
我无法找到有关此行为的文档,而且看起来很奇怪。
最佳答案
groovy 解析器需要一些信息来确定要执行的方法。
所以如果你写:
test('yet', 'another good', anything:'notneeded')
这被翻译成:
test([anything:'notneeded'], 'yet', 'another good')
即所有命名参数样式的参数(带有冒号)都放入映射中并放置在参数列表的开头。所有剩余的参数都放置在此之后。
所以 Groovy 现在寻找签名
test(Map, String, String)
并正确找到您的方法。如果没有命名参数,则不会发生此转换,签名将为
test(String, String)
,它没有匹配方法。所以解决方案是创建一个额外的方法来匹配没有命名参数的调用:
def test(some, thing='default value'){
test([:], some, thing)
}
这样,既支持命名调用又支持未命名调用。
关于groovy - 如何在 Groovy 方法中使用可选的命名参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54095999/