The used method reference has return type Integer. But an incompatible String is allowed in the following example.
How to fix the method <
This answer is based on the other answers which explain why it does not work as expected.
The following code solves the problem by splitting the bifunction "with" into two fluent functions "with" and "returning":
class Builder {
...
class BuilderMethod {
final Function getter;
BuilderMethod(Function getter) {
this.getter = getter;
}
Builder returning(R returnValue) {
return Builder.this.with(getter, returnValue);
}
}
BuilderMethod with(Function getter) {
return new BuilderMethod<>(getter);
}
...
}
MyInterface z = Builder.of(MyInterface.class).with(MyInterface::getLength).returning(1L).with(MyInterface::getNullLength).returning(null).build();
System.out.println("length:" + z.getLength());
// YIPPIE COMPILATION ERRROR:
// The method returning(Long) in the type BuilderExample.Builder.BuilderMethod is not applicable for the arguments (String)
MyInterface zz = Builder.of(MyInterface.class).with(MyInterface::getLength).returning("NOT A NUMBER").build();
System.out.println("length:" + zz.getLength());
(is somewhat unfamiliar)