Details
-
New Feature
-
Status: Closed
-
Major
-
Resolution: Fixed
-
2.4.1
-
None
Description
Groovy supports named-arg style constructor expressions if the object being created contains a Map-based constructor (which currently must be created explicitly) or a no-arg constructor plus appropriate setters. It would be good to have an explicit MapConstructor transform which allowed automatic creation of the Map-based constructor. This is useful for Java integration purposes but also allows various configuration options to be set and better support for final fields.
Such an AST transform would also potentially allow the Immutable AST transform to be built from components (outside the scope of this issue).
The transform should work like this:
import groovy.transform.* @TupleConstructor class Person { String first, last } @CompileStatic // optional @ToString(includeSuperProperties=true) @MapConstructor(pre={ super(args?.first, args?.last); args = args ?: [:] }, post = { first = first?.toUpperCase() }) class Author extends Person { String bookName } assert new Author(first: 'Dierk', last: 'Koenig', bookName: 'ReGinA').toString() == 'Author(ReGinA, DIERK, Koenig)' assert new Author().toString() == 'Author(null, null, null)'
The generated map constructor has a single argument args of type Map. In general, you should consider whether you want to guard against NPE exceptions as the above example shows.