我正在阅读Java 8 in Action.在3.5.2节中,有一个关于'void-compatibility rule'的段落:
如果lambda有一个语句表达式作为它的主体,它与一个返回void的函数描述符兼容(前提是参数列表也是兼容的).例如,以下两行都是合法的,即使添加List的方法返回一个布尔值而不是消费者上下文中预期的void(T - > void):
// Predicate has a boolean return
Predicate<String> p = s -> list.add(s);
// Consumer has a void return
Consumer<String> b = s -> list.add(s);
Run Code Online (Sandbox Code Playgroud)
你会如何描述'语句表达'?我以为这是陈述或表达.此虚空兼容性规则对我来说也不是100%清楚,你能想到其他任何例子吗?
我在Utils类中有以下可用方法:
protected <U> U withTx(Function<OrientGraph, U> fc) {
// do something with the function
}
protected void withTx(Consumer<OrientGraph> consumer) {
withTx(g -> {
consumer.accept(g);
return null;
});
}
Run Code Online (Sandbox Code Playgroud)
在myClass我的方法中:
withTx(g -> anotherMethod(g));
Run Code Online (Sandbox Code Playgroud)
第二段代码有一个编译错误:
The method withTx(Function<OrientGraph, Object>) is ambiguous for the type myClass
我想这来自编译器,它无法确定lambda是a Consumer还是a Function.是否有一种消除歧视这种情况的高尚方式?
无论方法anotherMethod返回什么(void,Object什么),我都不想使用这个返回值.
一种解决方案是:
withTx(g -> { anotherMethod(g); });
Run Code Online (Sandbox Code Playgroud)
但我想知道是否有更好的东西,因为这会触发SonarLint.