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

后端 未结 6 772
小蘑菇
小蘑菇 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 02:06

    The easy way to fix this is a type declaration on the method call to foo:

    Foo.foo(value -> true).booleanValue();
    

    Edit: I can't find the specific documentation about why this is necessary, pretty much just like everyone else. I suspected it might be because of primitive types, but that wasn't right. Regardless, This syntax is called using a Target Type. Also Target Type in Lambdas. The reasons elude me though, I can't find documentation anywhere on why this particular use case is necessary.

    Edit 2: I found this relevant question:

    Generic type inference not working with method chaining?

    It looks like it's because you're chaining the methods here. According to the JSR comments referenced in the accepted answer there, it was a deliberate omission of functionality because the compiler doesn't have a way to pass inferred generic type information between chained method calls in both directions. As a result, the entire type of erased by time it gets to the call to booleanValue. Adding the target type in removes this behavior by providing the constraint manually instead of letting the compiler make the decision using the rules outlined in JLS §18, which doesn't seem to mention this at all. This is the only info I could come up with. If anyone finds anything better, I'd love to see it.

提交回复
热议问题