Can't convert functional interface with generic method to lambda expression

It is not possible to convert a functional interface using a generic method to a lambda expression.
The following code works. This is without lambda expression, that is, using an 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 can't figure out how to use a lambda expression instead of an anonymous class.
After trying this, I used the hint shown in netbeans. I used the lamp shown to do this.

enter image description here

And this is what I got, ERROR.

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

      

An error is displayed. What's 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

      

+3


source to share


1 answer


The main problem is that you have a generic method instead of a generic interface. It doesn't make a lot of sense. Once you create a generic interface, 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 is very important for an interface that the interface is generic, since then it makes sense to have different implementations for different types. For this method to be generic, it is assumed that every implementation must be able to accept any value of any type, because the caller must specify it, which doesn't make sense if you then use a lambda expression with a specific type.

Your original version only works because you are declaring a generic type parameter Integer

... you are not specifying an implementation for the type Integer

. In other words, it is:



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

      

equivalent to:

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

      

... and I don't know a way to represent this as a lambda expression. Basically, I think your original interface is not suitable for lambda expressions.

+7


source







All Articles