Uploaded image for project: 'Groovy'
  1. Groovy
  2. GROOVY-7353

Groovy should provide a MapConstructor AST transform

    XMLWordPrintableJSON

Details

    • New Feature
    • Status: Closed
    • Major
    • Resolution: Fixed
    • 2.4.1
    • 2.5.0-alpha-1
    • xforms
    • 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.

      Attachments

        Activity

          People

            paulk Paul King
            paulk Paul King
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

            Dates

              Created:
              Updated:
              Resolved: