Lambda and method reference inference

Brian Goetz brian.goetz at oracle.com
Thu Dec 6 13:03:06 PST 2012


We did care -- a lot -- but in the other direction :(

This is one of those things that seems obvious at first but in reality 
has a poor cost-benefit balance.

First of all, in your example, you can get what you want with:

       A<Integer> c = (x, y) -> x + y;

If you take the trouble to provide explicit parameter types, you are 
saying "I want these exact types."  I can understand why you would want 
the compiler to "just do what I mean", but allowing this degree of 
flexibility unfortunately has a cost, and one of those costs is more 
inference failures in other cases.

At the same time, the benefit is low -- to fix the problem, either leave 
out the types and let the compiler infer them, or use the exact types 
you need (there's a good chance your IDE will provide them for you 
anyway.)  It's an easy and local fix.

We do allow this flexibility for method references because the user has 
no control over the types of the referred-to method the way he does with 
lambda parameter types.  And method references exhibit more inference 
failures.

The semantics are modeled on the following intuition:
  - typing for lambda expressions is like overriding a method;
  - typing for method references is like calling a method.


On 12/6/2012 1:56 PM, Remi Forax wrote:
> I think i've already raised this point in August during the face to face
> meeting and at that time nobody care, maybe this time, I will have more
> chance :)
>
> with
>      interface A<T> {
>        T foo(T a, T a2);
>      }
>
> this compile:
>      A<Integer> b = Integer::plus;    // with plus defined as int
> plus(int,int)
>
> but not this one:
>      A<Integer> c = (int x, int y) -> x + y;
>
>
> Can we, please, have the same rules for both method references and
> lambdas that have their type of parameters specified ?
>
> cheers,
> Rémi
>


More information about the lambda-spec-experts mailing list