Lambdas with implicit type parameters

Dan Smith daniel.smith at oracle.com
Wed Feb 6 13:44:18 PST 2013


Our status quo for handling of generic function descriptors (derived from functional interfaces with generic methods) was described by Brian back in April [1]: method references can target these functional interfaces, but lambdas, because they can declare no type parameters, cannot.

I remember discussions about an alternative approach, but I don't know whether it really got proper treatment from the EG, so I'll describe it here.  If anyone thinks this is a good enhancement to make, or if anybody remembers a previous, more in-depth discussion, please say so.

(Background: Remember that a lambda is treated like an override of the functional interface's method; generally speaking, the rules for a legal lambda correspond to the rules for a legal overriding declaration -- this means the lambda must declare the "same" (allowing for renaming) type parameters as the descriptor.  Also recall that we tried to find a syntax for generic lambdas, and failed to find anything acceptable.)

The idea: a lambda that targets a generic function descriptor may have an implicit type parameter declaration. Unlike most other forms of inference (using the term broadly), this is inference of a _declaration_ of a new name.  Sort of like wildcard capture.  The new names would be unmentionable, but if the lambda can be defined without needing to refer explicitly to a type parameter name (probably fairly common, especially when the lambda parameter types are inferred), that's fine.

Error messages would have to find a way to talk about these nameless tparams, of course (if, say, there's a type error in the lambda body).  Typically the functional interface declaration provides a reasonable name, although, in general, there can be multiple methods that describe the same descriptor with different type parameter names.

Example:

interface ListFactory {
  <T> List<T> make();
}

ListFactory f1 = ArrayList::new; // currently legal
ListFactory f2 = () -> new ArrayList<>(); // illegal currently, the enhancement would allow it
ListFactory f3 = () -> new ArrayList<T>(); // definitely illegal: T is not in scope

—Dan

[1] "Generic functional interfaces, generic method refs, and generic lambdas", 12 Apr 2012, from jsr-335-eg at jcp.org


More information about the lambda-spec-experts mailing list