我不明白为什么此代码有效:
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却能正常工作?
答案 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
}
};