Exceptions and lambda.
Dan Smith
daniel.smith at oracle.com
Tue Feb 5 22:29:43 PST 2013
If you're getting an error from the lambda expression, that's the expected behavior. Perhaps the error message could be improved, though...
This is not actually an exception problem: we simply don't allow lambda expressions to have type parameters. There's no syntax to introduce them, and if we inferred the declaration (something we thought about), it would be impossible or very confusing to talk about the type variable (e.g., give the lambda parameter an explicit type).
The implication is that the only way to instantiate a functional interface that has a generic method (well, excluding the boring approach of declaring a class) is to use a method reference.
If you haven't already done so, you'll probably be interested in testing the equivalent examples with the type parameters lifted to the interface level ("interface G1<E extends Exception>"). That should have less surprising behavior.
—Dan
On Feb 5, 2013, at 9:36 PM, Srikanth S Adayapalam <srikanth_sankaran at in.ibm.com> wrote:
> The following lambda expression does not compile with 8b74, while the
> implementation of the method in a class does compile:
>
> // ------------
> interface G1 {
> <E extends Exception> Object m(E p) throws E;
> }
> interface G2 {
> <F extends Exception> String m(F q) throws Exception;
> }
> interface G extends G1, G2 {}
>
> // G has descriptor <F extends Exception> ()->String throws F
>
> public class X {
>
> G g = (x) -> { // Elided type is inferred from descriptor to be F
> throw x; // ~== throw new F()
> };
> }
>
> class Y implements G {
> public <T extends Exception> String m(T t) throws T {
> throw t;
> }
> }
> // -----------------------
>
> Is this a bug in the implementation or the specification ?
> Since the lambda cannot refer to the type variables of the
> descriptor by name nor declare its own, if 8b74 behavior is
> correct, that would mean that, no checked exceptions could
> be thrown from a lambda if the descriptor of the target
> interface method mentions a type variable in throws clause.
>
> My analysis is that the lambda should be accepted as it does
> not manufacture any fresh exceptions and simply throws an
> exception that is known to have satisfied the constraints at
> the invocation site, i.e no additional/unexpected surprises
> are there due the lambda throwing the object it was handed.
>
> Thanks in advance for your clarification.
> Srikanth.
More information about the lambda-spec-experts
mailing list