Java – the functional interface of a generic method cannot be converted to a lambda expression
The functional interface of a generic method cannot be converted to a lambda expression
public interface Pro{ public <T> void callee(T t); } public void fun(Pro obj){} public void implement() { fun(new Pro() { @Override public <Integer> void callee(Integer t){} }); }
I can't understand how to use lambda expressions instead of anonymous classes After I tried it myself, I used the prompt displayed in NetBeans I use the bulb shown to do this
That's what I got, a mistake
public void implement() { fun((Integer t) -> { }); }
It displays errors What is the correct lambda expression used here? This is an error:
one\LambdaScopeTest.java:18: error: incompatible types: invalid functional descriptor for lambda expression fun((Integer t) -> { ^ method <T>(T)void in interface Pro is generic where T is a type-variable: T extends Object declared in method <T>callee(T) Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
Solution
The main problem is that you have a common method rather than a common interface It doesn't make much sense As long as you make the interface generic, it will work:
@FunctionalInterface interface Pro<T> { void callee(T t); } public class Test { public static <T> void fun(Pro<T> obj){} public static void main(String[] args) { fun((Integer t) -> {}); } }
Interfaces are generic and more meaningful because they make sense for different implementations of different types For generic methods, it is recommended that each implementation should be able to accept any value of any type, because the caller will specify it - it doesn't make sense if you then use a lambda expression with a specific type
Your original version only works because you declared a generic type parameter named integer... You did not specify an implementation for the integer type In other words, this:
fun(new Pro() { @Override public <Integer> void callee(Integer t){} });
amount to:
fun(new Pro() { @Override public <T> void callee(T t){} });
... I don't know how to express it as a lambda expression Basically, I don't think your original interface is suitable for lambda expressions