2

I have a Functional Interface in the code below which has one abstract method and one object method override. So when I write Lambda expression for that , how can I implement my equals method.

import static java.lang.System.out;

public class Test {
    public static void main(String[] args) {
        AddToString test = a -> (a + " End");
        out.println(test.stringManipulation("some string"));
        out.println(test.increment(5));
        out.println(test.equals(null));
    }
}

@FunctionalInterface
interface AddToString {
    String stringManipulation(String a);
    default int increment(int a) { return a+1; }
    @Override
    public boolean equals(Object obj);
} 

One way to do that is to create Anonymous class like given below, but is there a better method using lambda expressions -

public class Test {
    public static void main(String[] args) {
        AddToString test = new AddToString() {
            public String stringManipulation(String a) {
                return a + " End";
            }
            @Override
            public boolean equals(Object Obj) {
                //Just testing whether it overrides
                return 5==5;
            }
        };
        out.println(test.stringManipulation("some string"));
        out.println(test.increment(5));
        out.println(test.equals(null));
    }
}
1
  • 1
    How should a plausible lambda expression based equals implementation, which can’t access this nor any of the interface’s methods look like? Even an anonymous class based implementation is hard to imagine. Commented Jul 13, 2016 at 7:49

1 Answer 1

7

You can't. If you need to override equals, you'll need to create a class (anonymous or otherwise), you can't do it with a lambda.

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

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.