javaspringspring-bootintellij-idea

Shortcut to generate setters with `this` as return type


Let's say I have a class HomeWork and is annotated with @Builder

@Data
@Builder
@FieldDefaults(level = AccessLevel.PRIVATE)
class HomeWork {
    List<Question> questions;
    double totalMarks;

    double receivedMarks;
    boolean passed;
}

I can create the instance of HomeWork using builder:

...

HomeWork homeWork = HomeWork.builder()
.questions(List.of(questions))
.totalMarks(100.0)
.build()

Now if I have to update the receivedMarks and passed properties then I will have to call the setters of them like this:

homeWork.setReceivedMarks(85.0);
homeWork.setPassed(true);

This is fine but could be better, if I had setters which would return this so we could chain the setters:

public HomeWork setReceivedMarks(double receivedMarks) {
   this.receivedMarks = receivedMarks;
   return this;
}
...
setReceivedMarks(85).setPassed(true);

So I wanted to know if there is any shortcut way to generate such setters in Intellij IDE? If not then is there any other way to chain the setters?


Solution

  • You can use Lombok annotation Accessors, which accept parameter chain=true which will result in setters returning this variable.

    Example:

    @Data
    @Builder
    @FieldDefaults(level = AccessLevel.PRIVATE)
    @Accessors(chain = true)
    class HomeWork {
         ...
    
    }