In fact, as Hossein Nasr already explained, Lombok cannot know whether there are subclasses that do not have toBuilder=true
.
Lombok could require all direct subclasses of an abstract class to also use toBuilder
by adding an abstract toBuilder()
method on the abstract class. However, there may be use-cases where subclasses should not have a toBuilder
(although I haven't seen any good examples of those). Furthermore, indirect subclasses may still lack the toBuilder
feature. Therefore, lombok does not enforce toBuilder
on subclasses of abstract classes.
Good news is that you can easily work around it in your case (only direct subclasses) by adding the abstract toBuilder()
method to your abstract class Parent
manually:
@SuperBuilder(toBuilder = true)
public abstract class Parent {
public abstract ParentBuilder<?, ?> toBuilder();
}
With this change, your copy
method compiles and works as expected.
If you also have indirect subclasses, you have to find other means to ensure they also have @SuperBuilder(toBuilder = true)
. If those would not have this annotation, you may experience strange behavior (e.g. calling copy()
will instantiate a different class).
Disclaimer: I implemented the @SuperBuilder
feature.