简体   繁体   中英

Cannot convert functional interface with generic method into lambda expression

Cannot convert functional interface with generic method into lambda expression.
Following code is working. It is without lambda expression ie using anonymous class.

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 cannot understand how to use lambda expression instead of anonymous class.
After trying it myself I used the hint shown in netbeans. I used the shown bulb to do it.

在此输入图像描述

And here is what I got, an ERROR.

public void implement() {
    fun((Integer t) -> {
    });
}

It is showing error. What is the correct lambda expression to be used here?
Here is the 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

The main problem is that you've got a generic method instead of a generic interface . That doesn't make a lot of sense. As soon as you make the interface generic instead, it works:

@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) -> {});
    }
}

It makes much more sense for the interface to be generic, as then it makes sense to have different implementations for different types. For the method to be generic suggests that every implementation should be able to accept any value of any type, because the caller would be specifying it - which doesn't make sense if you then use a lambda expression with a specific type.

Your original version is only working because you're declaring a generic type parameter called Integer ... you're not specifying an implementation for the Integer type. In other words, this:

fun(new Pro() {
    @Override
    public <Integer> void callee(Integer t){}
});

is equivalent to:

fun(new Pro() {
    @Override
    public <T> void callee(T t){}
});

... and I don't know of a way of representing that as a lambda expression. Basically, I think your original interface is inappropriate for lambda expressions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM