PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, November 4, 2022

[FIXED] How does Java lambda automatically match to an interface's function?

 November 04, 2022     function, interface, java, lambda, types     No comments   

Issue

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?


Solution

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.



Answered By - Jakubeeee
Answer Checked By - Katrina (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing