Builder instance method does not return 'this'


The problem

This check identifies instance methods in builder classes, and requires that they either return this;, or are explicitly annotated with @CheckReturnValue.

Instance methods in builders typically return this, to allow chaining. Ignoring this result does not indicate a bug. For example, both of the following are fine:

Foo.Builder builder = Foo.builder();
builder.setBar("bar"); // return value is deliberately unused
Foo.Builder builder =

Rarely, a builder method may return a new instance, which should not be ignored. This check requires these methods to be annotated with @CheckReturnValue:

class Builder {
  Builder setFoo(String foo) {
    return new Builder(foo); // returns a new builder instead of this!

This check allows the enforcement to assume the return value of instance methods in builders can safely be ignored, unless the method is explicitly annotated with @CheckReturnValue.


Suppress false positives by adding the suppression annotation @SuppressWarnings("BuilderReturnThis") to the enclosing element.