大家都知道龙延伸Number。那么为什么不编译呢?
以及如何定义方法with,使程序无需任何手工转换就可以编译?
import java.util.function.Function;
public class Builder<T> {
static public interface MyInterface {
Number getNumber();
Long getLong();
}
public <F extends Function<T, R>, R> Builder<T> with(F getter, R returnValue) {
return null;//TODO
}
public static void main(String[] args) {
// works:
new Builder<MyInterface>().with(MyInterface::getLong, 4L);
// works:
new Builder<MyInterface>().with(MyInterface::getNumber, (Number) 4L);
// works:
new Builder<MyInterface>().<Function<MyInterface, Number>, Number> with(MyInterface::getNumber, 4L);
// works:
new Builder<MyInterface>().with((Function<MyInterface, Number>) MyInterface::getNumber, 4L);
// compilation error: Cannot infer ...
new Builder<MyInterface>().with(MyInterface::getNumber, 4L);
// compilation …Run Code Online (Sandbox Code Playgroud) Why is
public <R, F extends Function<T, R>> Builder<T> withX(F getter, R returnValue) {...}
Run Code Online (Sandbox Code Playgroud)
more strict then
public <R> Builder<T> with(Function<T, R> getter, R returnValue) {...}
Run Code Online (Sandbox Code Playgroud)
This is a follow up on Why is lambda return type not checked at compile time.
I found using the method withX() like
.withX(MyInterface::getLength, "I am not a Long")
Run Code Online (Sandbox Code Playgroud)
produces the wanted compile time error:
The type of getLength() from the type BuilderExample.MyInterface is long, this is incompatible with the descriptor's return type: …