Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy: Named parameter constructors

Tags:

groovy

I found really cool that one can do:

class Foo {
    String name
}

def foo = new Foo(name:"Test")

But, it only works when my file name matches the class name. If I have a file with a bunch of classes like:

class AllClassesInOneFile {
    class Bar {}
    class Foo {
      String name
    }
}

def foo = new Foo(name:"Test")

Now, it does not work anymore I get a java.lang.IllegalArgumentException: wrong number of arguments

I wonder if it is still possible to invoke named parameter argument style with scripts and nested classes.

Regards

like image 384
Vinicius Carvalho Avatar asked Feb 19 '13 18:02

Vinicius Carvalho


2 Answers

Seems like Groovy needs explicit reference to an instance of the outer class:

class Baz {
    class Bar {}
    class Foo {
      String name
    }
}

def baz = new Baz()

def f = new Baz.Foo(baz, [name: "john doe"])

assert f.name == "john doe"
like image 93
Will Avatar answered Nov 13 '22 15:11

Will


Non-static nested object can't exist without instance of the outer class. The same in java. Just change nested object to static.

like image 43
Maksim Korneichik Avatar answered Nov 13 '22 13:11

Maksim Korneichik