1

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"

Pramod S. Nikam
  • 4,271
  • 4
  • 38
  • 62

2 Answers2

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.

Ian Roberts
  • 120,891
  • 16
  • 170
  • 183
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.

Community
  • 1
  • 1
assylias
  • 321,522
  • 82
  • 660
  • 783