我怎么能有一个默认参数的方法,我可以在Groovy中按名称覆盖?

时间:2014-06-02 19:10:54

标签: methods groovy named-parameters default-parameters

groovy中的构造函数允许使用命名参数,方法参数允许使用默认值,但我似乎无法使用默认参数值的方法使用命名参数。

理想情况下,我想要这样的事情:

def myMethod(def greeting = "Hello", def person = "World", def inflection = "!") {
    "${greeting} ${person}${inflection}"
}

assert myMethod() == "Hello World!"
assert myMethod(greeting: "Hi") == "Hi World!"
assert myMethod(inflection: "?", person: "bob") == "Hello Bob?"
assert myMethod("Sup") == "Sup World!"
assert myMethod("Word", "Dawg") == "Word Dawg!"

这是我能够得到的最接近的,但它非常丑陋,并且感觉不那么时髦#34;并且在所有情况下都不能完全发挥作用:

def myMethod(Map vars = [:]){

    vars.greeting = vars.greeting ?: "Hello"
    vars.person = vars.person ?: "World"
    vars.inflection = vars.inflection ?: "!"

    "${vars.greeting} ${vars.person}${vars.inflection}"
}

2 个答案:

答案 0 :(得分:4)

Groovy没有真正的命名参数,并且它不会比上一个代码段更好。

答案 1 :(得分:3)

如果不是那么丑陋的话。 :)

def myMethod(Map params = [:], String... args) {
    "${params.greeting ?: args?.size() > 0 ? args[0] : "Hello"} ${params.person ?: args?.size() > 1 ? args[1] : "World"}${params.inflection ?: args?.size() > 2 ? args[2] : '!'}"
}

assert myMethod() == "Hello World!"
assert myMethod(greeting: "Hi") == "Hi World!"
assert myMethod(inflection: "?", person: "Bob") == "Hello Bob?"
assert myMethod("Sup") == "Sup World!"
assert myMethod("Word", "Dawg") == "Word Dawg!"
assert myMethod("Word", "Dawg", '?') == "Word Dawg?"
assert myMethod(greeting: "Hi", person: 'John') == "Hi John!"

这是一个更加开发友好的版本,并且它在映射到所需方法签名方面更为明显:

def myMethod(Map params = [:], Object... args) {

    def greeting = params.greeting ?: args?.size() > 0 ? args[0] : "Hello"
    def person = params.person ?: args?.size() > 1 ? args[1] : "World"
    def inflection = params.inflection ?: args?.size() > 1 ? args[1] : "!"

    "${greeting} ${person}${inflection}"
}