Search code examples
javaconsumer

Java consumer with return


I don't understand why this code is working:

class Resource {
    private Resource() {
        System.out.println("created...");
    }
    public Resource op1() {
        System.out.println("op1");
        return this;
    }
    public Resource op2() {
        System.out.println("op2");
        return this;
    }
    private void close() {
        System.out.println("clean up...");
    }
    public static void use(Consumer<Resource> block) {
        Resource resource = new Resource();
        try {
            block.accept(resource);
        }
        finally {
            resource.close();
        }
    }
}

// method call

public class App 
{
    public static void main( String[] args )
    {
      Consumer<Resource> block = resource -> resource.op1().op2(); //here
      Resource.use(block);
    }
}

Consumer should accept one parameter and return void. But in this example Consumer take one parameter(resource) and return this parameter. Why it is working although I return resource instance instead of void?


Solution

  • Your Consumer<Resource> block = resource -> resource.op1().op2(); is equivalent to:

    Consumer<Resource> block = new Consumer<Resource>() {
            @Override
            public void accept(Resource resource) {
                resource.op1().op2();  // there is no return statement
            }
        };