2

Suppose I have interface A which has only one method declared like below:

interface A{        
    void print();           
}

now with old java style we'll use this in anonymous way like below:

new A() {           
        @Override
        public void print() {
            System.out.println("in a print method");                
        }           
};

and with lambda expression we'll use it like below:

() -> "A1";

now my question is if interface A has two methods declared like below:

interface A{        
   void print();    
   void display();          
}

and its old way of anonymous function utilization is like below:

  new A() {         
        @Override
        public void print() {
            System.out.println("in print");

        }

        @Override
        public void display() {
            System.out.println("in display");

        }       

    };

Now how to convert display method to lambda? or we are not allowed to do this; if not why not? Why cant we represent it like

print() -> "printing"

and

display() -> "displaying"

0

2 Answers 2

9

You can't. A lambda expression can only be used for a "functional" interface - one that has only one non-default method.

For the "why" you'd have to ask the language designers, but my take on it is that lambda expressions are a shorthand for single blocks of code, whereas a group of related blocks treated as a unit would be better represented as a proper class. For cases like your example in the question, the real answer would be to modify the API so that instead of using a single A interface with two methods it uses two separate functional interfaces for the two functions APrinter and ADisplayer, which could then be implemented by separate lambdas.

Sign up to request clarification or add additional context in comments.

Comments

2

You can't but you can "transform" A into a functional interface by providing a default implementation for one of the two methods, for example:

public interface B extends A {
    default void print() {}
}

B lambda = () -> displaySomething();

Alternatively you can provide a static factory.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.