Why is lambda return type not checked at compile time?

后端 未结 4 2083
小蘑菇
小蘑菇 2020-12-29 18:54

The used method reference has return type Integer. But an incompatible String is allowed in the following example.

How to fix the method <

4条回答
  •  青春惊慌失措
    2020-12-29 19:50

    This answer is based on the other answers which explain why it does not work as expected.

    SOLUTION

    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)

提交回复
热议问题