Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I define Lambda Expression for an interface with more than one method?

I can not define a lambda expression for an interface with multiple methods shown in the code below.

interface Interface{
    public void st1();
    public String ra(String p);
}

I can define a lambda expression for a single-method interface.

interface Interface{
    public String ra(String p);
}

public static void main(String[] args) {
    Interface r = (x)->{
        return x;
    };
    String getValue = r.ra("string");
    System.out.println(getValue);
}

But how can I define a lambda Expression for multiple methods?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Functional interface

You’re thinking about functional interfaces. Anonymously defining a class with a lambda expression is a syntactic sugar that’s only available for interfaces with a single method. If you have more than one method, you’ll have to resort to a good old fashioned anonymous class:

Interface r = new Interface() {
    public void st1() {
        // do something;
    }

    public String ra(String p) {
        return p;
    }
}

For more info, see articles such as:

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading