Groovy Goodness: @Builder Definition with Extra Type Checks

We have seen some features of the @Builder AST transformation in previous and other blog post. We can use another strategy to let the AST transformation generate a class where the class only has a constructor that accepts a builder class. And with @CompileStatic we can even make sure that all required properties must have a value set by the builder before the constructor accepts the argument. We use the builderStrategy annotation parameter and set it to InitializerStrategy:

We can customize which properties need to be set with the includes and/or excludes annotation parameter. We can also customize the name of the method that create the builder instance with the parameter builderMethodName:

Code written with Groovy 2.3.

Original article

This entry was posted in Groovy and tagged , by mrhaki. Bookmark the permalink.

About mrhaki

My name is Hubert A. Klein Ikkink also known as mrhaki. I work at the great IT company JDriven. Here I work on projects with Groovy & Grails, Gradle and Spring. At JDriven we focus on SpringSource technologies. All colleagues want to learn new technologies, support craftmanship and are very eager to learn. This is truly a great environment to work in. You can contact me via Google+ or @mrhaki.

4 thoughts on “Groovy Goodness: @Builder Definition with Extra Type Checks

  1. Thanks for these useful posts!
    Is there a way to combine the Builder with the @Immutable transformation? I’ve tried, but it won’t compile. Perhaps with some other builderStrategy?

    • I think you can combine both if you use the SimpleStrategy:

      @Builder(builderStrategy = SimpleStrategy, prefix = '')
      class User {
      String name
      int age

      def u = new User().name('mrhaki').age(40)

      u.age = 41 // ReadOnlyException

Leave a Reply

Your email address will not be published. Required fields are marked *