Why is lambda return type not checked at compile time?

后端 未结 4 2091
小蘑菇
小蘑菇 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:28

    Its the type inference that is playing its role here. Consider the generic R in the method signature:

     Builder with(Function getter, R returnValue)
    

    In the case as listed:

    Builder.of(MyInterface.class).with(MyInterface::getLength, "I am NOT an Integer");
    

    the type of R is successfully inferred as

    Serializable, Comparable>
    

    and a String does imply by this type, hence the compilation succeeds.


    To explicitly specify the type of R and find out the incompatibility, one can simply change the line of code as :

    Builder.of(MyInterface.class).with(MyInterface::getLength, "not valid");
    

提交回复
热议问题