Initialize two fields at once with Lombok builder

Viewed 465

I'm trying to populate two fields in a class by using only one field in a Lombok builder.

e.g.

@Builder
public class Foo {
   @NonNull
   private final double bar1;

   @NonNull
   private final double bar2;

}

I want

Foo.builder().bar1(0.0).build();

to also set bar2 to the same value as bar1.

Thanks

2 Answers

You can manually implement the setter method in the builder class such that it sets both fields:

@Builder
public class Foo {
   @NonNull
   private final double bar1;

   @NonNull
   private final double bar2;

   public static class FooBuilder {
       public FooBuilder bar1(double bar1) {
           this.bar1 = this.bar2 = bar1;
           return this;
       }
   }
}

The rest of the builder code will still be generated by Lombok. You'll just have to write those methods you want to replace.

However, I'm not sure if this is worth it: Foo.builder().bar1(1).bar2(2).build() will have a different result than Foo.builder().bar2(2).bar1(1).build(). This could introduce bugs that are very difficult to spot. At least make sure you document it properly.

Nice thought, but lombok @builder does not support that. You have to assign values individually. You can see your compiled class which will make you clear what code lombok generates after compilation.

However, if you really want to initialize two fields at once, you would need to implement your own builder pattern.

Related