I want to write an implementation of a functional, non-generic interface which has a generic method. The implementation needs to be an inline closure and concise.
As a simplified example
@FunctionalInterface interface Fn {
<R> R fn(R arg);
}
public class Scratch {
Fn id = arg -> arg;
//Fn nul = arg -> null;
//Fn requiresNonNull = ...
}
which gives
/Scratch.java:5: error: incompatible types: invalid functional descriptor for lambda expression
Fn id = arg -> arg;
^
method <R>(R)R in interface Fn is generic
where R is a type-variable:
R extends Object declared in method <R>fn(R)
1 error
(In reality the parameter would be a generic interface with a methods that had a return type of R
.)
Is there a workaround without heading back to the verbosity of an anonymous inner class?
There is an apparently similar question, "Cannot convert functional interface with generic method into lambda expression", but that stems from using a type parameter called Integer
instead of something conventional like T
, and Jon Skeet's accepted answer says he doesn't know a solution to my problem.
There is also a long discussion, "Functional interface confusion", that fails to answer this question. It can't be "a verbose anonymous inner classes is best here", can it?
Generic lambdas aren't legal, but generic method references are. You can cut down a bit on the verbosity of anonymous classes by creating helper methods instead: