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? Just having 1 and only 1 function in interface definition?