Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/extjs/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/kubernetes/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Groovy命名参数和默认参数_Groovy_Arguments_Argument Passing - Fatal编程技术网

Groovy命名参数和默认参数

Groovy命名参数和默认参数,groovy,arguments,argument-passing,Groovy,Arguments,Argument Passing,Groovy支持默认参数和命名参数。我只是没看到他们在一起工作 我需要一些类来支持使用简单的非命名参数和命名参数的构造,如下所示: def a1 = new A(2) def a2 = new A(a: 200, b: "non default") class A extends SomeBase { def props A(a=1, b="str") { _init(a, b) } A(args) { // use the

Groovy支持默认参数和命名参数。我只是没看到他们在一起工作

我需要一些类来支持使用简单的非命名参数和命名参数的构造,如下所示:

def a1 = new A(2)
def a2 = new A(a: 200, b: "non default")

class A extends SomeBase {
    def props
    A(a=1, b="str") { 
        _init(a, b)
    }

    A(args) { 
       // use the values in the args map:
       _init(args.a, args.b)
       props = args
    }

    private _init(a, b) {
    }

}

同时支持两者通常是好的做法吗?上面的代码是唯一的方法吗?

给定的代码会导致一些问题。特别是,它将使用单个对象参数生成两个构造函数。第一个构造函数生成的字节码等效于:

A() // a,b both default
A(Object) // a set, b default
A(Object, Object) // pass in both
第二个生成:

A(Object) // accepts any object
您可以通过添加一些类型来解决此问题。尽管groovy具有动态类型,但方法和构造函数中的类型声明仍然很重要。例如:

A(int a = 1, String b = "str") { ... }
A(Map args) { ... }

至于好的实践,我只需要使用一个或注释。它们将自动提供正确的属性映射和位置参数构造函数。TupleConstructor仅提供构造函数,Canonical应用了一些其他与
equals
hashCode
、和
toString

有关的最佳实践。不幸的是,您的URL现在已失效,但应在此处找到它们: