Groovy Sample code2

Named parameters and Groovy constructors

Search for: Named parameters and Groovy constructors

Named parameters and Groovy methods

Search for: Named parameters and Groovy methods

Named argument constructors are documented here


class PersonWOConstructor {                                  
    String name
    Integer age
}

def person4 = new PersonWOConstructor()                      
def person5 = new PersonWOConstructor(name: 'Marie')         
def person6 = new PersonWOConstructor(age: 1)                
def person7 = new PersonWOConstructor(name: 'Marie', age: 2)

When no (or a no-arg) constructor is declared, Groovy replaces the named constructor call by a call to the no-arg constructor followed by calls to the setter for each supplied named property. So, you might be better off using the Map constructor if your properties are declared as final (since they must be set in the constructor rather than after the fact with setters).

What is a map constructor in groovy?

Search for: What is a map constructor in groovy?

Map based constructors are elaborated here

MapConstructor annotation is documented here

This will not generate the constructor that takes a map as an input

Either you have to write that yourself

Or use the @MapConstructor as an annotation


def foo(Map args) 
{ 
  "${args.name}: ${args.age}" 
}

It takes a map, hopefully keys are name and age, and returns a concatenated string.


foo(name: 'Marie', age: 1)