有回报的Java使用者

时间:2019-02-03 14:39:08

标签: java consumer

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

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

消费者应接受一个参数并返回void。但是在此示例中,使用者使用一个参数(资源)并返回此参数。为什么返回资源实例而不是void却能正常工作?

1 个答案:

答案 0 :(得分:0)

您的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
        }
    };