Home > Software engineering >  How does Java lambda automatically match to an interface's function?
How does Java lambda automatically match to an interface's function?

Time:06-19

I'm testing to see if java's lambda will match interface function, I wrote code below, it works. I've interface MyHandler, and its myFunction. On construction a Java lambda is converted into an implementer of my interface.

package mygroup;
interface MyHandler{
    void myFunction(int i);
}
class Worker{
    private final MyHandler handler;
    public Worker(MyHandler h){
        handler = h;
    }
    public void work(int i){handler.myFunction(i);};
}
public class TestLambda {
    public static void main(String[] args) {
        Worker worker = new Worker(i -> System.out.println(i));
        worker.work(3);
    }
}

Program will print 3. So far so good, but if I add some other function declaration in MyHandler like below:

interface MyHandler{
    void myFunction(int i);
    void f(int i, int j);
}

The that lambda in Thread constructor will fail to compile, saying that

The constructor Worker((<no type> i) -> {}) is undefinedJava(134217858)
The target type of this expression must be a functional interfaceJava(553648781)

So when could Java compiler decide that a lambda can match the type of MyHandler, no matter my function name is? Justing having 1 and only 1 function in interface definition?

Thanks a lot.

CodePudding user response:

Lambdas are implementations of "functional interfaces". A functional interface is an interface that has exactly one abstract method. The name of the method does not matter. Your original interface with only one method fulfills that condition. Your second version that has two different abstract methods does not fulfill the condition and the compiler refuses to use a lambda as an implementation of MyHandler.

Note that, if you want a very useful compiler check on the side of the interface, you can add the optional @FunctionalInterface annotation. The compiler will verify the exactly one abstract method condition:

@FunctionalInterface
interface MyHandler{
    void myFunction(int i);
}

With this annotation, it will fail to compile if the amount of abstract methods is not equal to 1.

  • Related