简体   繁体   中英

Groovy named positional argument with default value

I have this code:

def myFunc(arg1, arg2="default arg2", arg3="default arg3") {
    println("arg1: ${arg1}")
    println("arg2: ${arg2}")
    println("arg3: ${arg3}")

}

myFunc(1, arg3="foo")

My desired output:

arg1: 1
arg2: default arg2
arg3: foo

Actual output:

arg1: 1
arg2: foo
arg3: default arg3

I want to override the last argument without changing the middle arg2 which has a default value I need. I cannot use classes. What are my options?

This is not possible in groovy, The right most optional parameter is dropped first and so on and so forth.

Better explanation: https://mrhaki.blogspot.com/2009/09/groovy-goodness-parameters-with-default.html

The implementor would need to pass in the default 2nd param when invoking this method.

As already answered, this does not work - groovy has no named arguments. One thing people often confuse for named arguments, is the passing of maps. Eg you can have the defaults be merged with the arguments and come close to what you are after:

def myFunc(Map kwargs = [:]) {
    def args = [arg1: "a1", arg2: "a2", arg3: "a3"].tap{putAll(kwargs)}
    println([args.arg1, args.arg2, args.arg3])
}

myFunc(arg3: "new a3")
// => [a1, a2, new a3]

You can also check for the incoming keys beforehand, that they are in the default to notify the consumer at least at runtime, that they are sending unknown keys.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM