我不明白为什么这段代码有效: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 callpublic class App { public static void main( String[] args ) { Consumer<Resource> block = resource -> resource.op1().op2(); //here Resource.use(block); }}消费者应该接受一个参数并返回 void。但在此示例中,消费者采用一个参数(资源)并返回此参数。尽管我返回资源实例而不是 void,为什么它仍然有效?
1 回答
慕莱坞森
TA贡献1810条经验 获得超4个赞
你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
}
};
添加回答
举报
0/150
提交
取消