猿问

有回报的Java消费者

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


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,为什么它仍然有效?


烙印99
浏览 73回答 1
1回答

慕莱坞森

你Consumer<Resource> block = resource -> resource.op1().op2();相当于:Consumer<Resource> block = new Consumer<Resource>() {&nbsp; &nbsp; &nbsp; &nbsp; @Override&nbsp; &nbsp; &nbsp; &nbsp; public void accept(Resource resource) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; resource.op1().op2();&nbsp; // there is no return statement&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; };
随时随地看视频慕课网APP

相关分类

Java
我要回答