Why is this type inference not working with this Lambda expression scenario?

后端 未结 6 771
小蘑菇
小蘑菇 2020-12-24 01:23

I have a weird scenario where type inference isn\'t working as I\'d expect when using a lambda expression. Here\'s an approximation of my real scenario:

stat         


        
6条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-24 01:56

    I don't know why but you need to add separate return type:

    public class HelloWorld{
    static class Value {
    }
    
    @FunctionalInterface
    interface Bar {
          R apply(Value value); // Return type added
    }
    
    static class Foo {
      public static  R foo(Bar callback) {
          return callback.apply(new Value());
      }
    }
    
    void test() {
      System.out.println( Foo.foo(value -> true).booleanValue() ); // No compile error here
    }
         public static void main(String []args){
             new HelloWorld().test();
         }
    }
    

    some smart guy probably can explain that.

提交回复
热议问题