0

I have following code:

public interface Listener {
    void onRemoved(int position);
    void onAdded();
}

MyClass:

/* constructor */
public Test(Listener listener) {}

AnotherClass:

Test test = new Test(How to implement the onRemoved and onAdded here using lambda?)
1
  • 1
    you cannot unless both of those are supposed to be defined(are abstract). maybe just use anonymous class there. Commented Aug 5, 2019 at 8:33

4 Answers 4

3

In java8 lambda is being used to implement Functional Interfaces so by definition it must contain only one abstract method - therefore the answer is you cannot.

What you need here is an Anonymous Class instance

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

Comments

0

Lambda expressions can be used only with SAM (Single Abstract Method) interfaces, unfortunately.

If you need to achieve lambda-like-semantics for interfaces with more than a single abstract method, you need to fall back to old-school anonymous inner classes:

Listener listener = new Listener() {
        @Override
        public void onRemoved(int position) {
            // ...
        }

        @Override
        public void onAdded() {
            // ...
        }
    };

Comments

0
public class Main {
    public static void main(String[] args) {
        Test test = new Test(new Listener() {
            @Override
            public void onRemoved(int position) {
                System.out.println("onRemoved" + position);
            }

            @Override
            public void onAdded() {
                System.out.println("onAdded");
            }
        });

        test.getListener().onAdded();
        test.getListener().onRemoved(1);
    }
}

you can't use lambda, only like this.

Comments

0

A lambda expression is syntactic-sugar to implement the only method contained inside a functional interface. If your interface has multiple methods that need to be implemented, you cannot use lamda expressions to implement them. This makes sense as if it were possible to do so, then how would the compiler ascertain which method has been implemented?

Imagine this:

public interace TestInterface {
   public int foo1(int arg);
   public int foo2(int arg);
}

Imagine doing this:

TestInterace impl = () -> 1;  //which method's implementation does this lamda represent

You can use anonymous inner classes to implement your interface.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.