Why is lambda return type not checked at compile time?

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

    In the first example, MyInterface::getLength and "I am NOT an Integer" helped to resolve the generic parameters T and R to MyInterface and Serializable & Comparable>respectively.

    // it compiles since String is a Serializable
    Function function = MyInterface::getLength;
    Builder.of(MyInterface.class).with(function, "I am NOT an Integer");
    

    MyInterface::getLength is not always a Function unless you explicitly say so, which would lead to a compile-time error as the second example showed.

    // it doesn't compile since String isn't an Integer
    Function function = MyInterface::getLength;
    Builder.of(MyInterface.class).with(function, "I am NOT an Integer");
    

提交回复
热议问题