Java 消费者 return

Java consumer with return

我不明白为什么这段代码有效:

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);
    }
}

消费者应该接受一个参数并且return无效。但是在这个例子中,Consumer 取一个参数(resource)并且 return 这个参数。为什么尽管我 return 资源实例而不是 void 但它仍然有效?

您的 Consumer<Resource> block = resource -> resource.op1().op2(); 相当于:

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