mooL mooL - 4 months ago 8
Java Question

What happens if I return the 'this' keyword?

How does it work and how do I do it? I have been looking all over for this but I can't find an explanation for returning 'this'.

public class MyClass
int i = 1;
public static void main(String [] args) {
MyClass object = new MyClass();
object.method(3);
}
public MyClass method(int i) {
this.i = i;
return this;
}

Answer

What happens if I return the 'this' keyword?

Nothing particularly special. this is just a reference to the current object. If you return it, you're returning that reference, just like when you return any other object reference from a method.

It's commonly done with APIs that allow chaining calls on the same object, e.g.:

this.doThis().doThat().doTheOther();

...where all three of those methods are all in the same class and (because the first two return this) called on the same instance. The single statement above is exactly the same as:

this.doThis();
this.doThat();
this.doTheOther();

It's particularly useful for the Builder pattern of complex object construction (but that's just one application, it has several others). Consider this example: Live Copy

class Thingy {
    private String state;

    private Thingy(String s1, String s2, String s3) {
        this.state = s1 + "/" + s2 + "/" + s3;
    }

    public String getState() {
        return this.state;
    }

    public static class Builder {
        private String state1 = null;
        private String state2 = null;
        private String state3 = null;

        public Builder withState1(String s1) {
            this.state1 = s1;
            return this;
        }

        public Builder withState2(String s2) {
            this.state2 = s2;
            return this;
        }

        public Builder withState3(String s3) {
            this.state3 = s3;
            return this;
        }

        public Thingy build() {
            if (this.state1 == null) {
                throw new IllegalStateException("state1 is required");
            }
            if (this.state2 == null) {
                throw new IllegalStateException("state2 is required");
            }
            if (this.state3 == null) {
                throw new IllegalStateException("state3 is required");
            }
            return new Thingy(this.state1, this.state2, this.state3);
        }
    }
}

Then we use it like this:

Thingy t = new Thingy.Builder()
            .withState1("one")
            .withState2("two")
            .withState3("three")
            .build();
System.out.println(t.getState());

The output would be:

one/two/three

Without getting into talking about the Builder pattern too much, with that simple example we could just make the Thingy constructor public and expect people to give us three arguments. But the pattern is used when the constructor would get unwieldy (too many parameters, or parameters that are or are not required depending on the values of other parameters, etc.). And returning this make it possible to use Builder succinctly as in that example.

Comments