Groovy Sample code2

satya - 8/16/2018, 3:37:43 PM

Named parameters and Groovy constructors

Named parameters and Groovy constructors

Search for: Named parameters and Groovy constructors

satya - 8/16/2018, 3:37:55 PM

Named parameters and Groovy methods

Named parameters and Groovy methods

Search for: Named parameters and Groovy methods

satya - 8/16/2018, 3:39:26 PM

Named argument constructors are documented here

Named argument constructors are documented here

satya - 8/16/2018, 3:40:05 PM

Consider this


class PersonWOConstructor {                                  
    String name
    Integer age
}

satya - 8/16/2018, 3:40:58 PM

The following is valid


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

satya - 8/16/2018, 3:42:43 PM

Advice on empty constructors

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).

satya - 8/16/2018, 3:43:44 PM

What is a map constructor in groovy?

What is a map constructor in groovy?

Search for: What is a map constructor in groovy?

satya - 8/16/2018, 3:47:58 PM

Map based constructors are elaborated here

Map based constructors are elaborated here

satya - 8/16/2018, 3:49:55 PM

MapConstructor annotation is documented here

MapConstructor annotation is documented here

satya - 8/16/2018, 3:51:46 PM

Defining an explicit constructor

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

satya - 8/16/2018, 3:53:35 PM

Similarly consider this method


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

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

satya - 8/16/2018, 3:53:56 PM

That method can be invoked as this


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