I am implementing equals method for a class, which has a member of a Functional Interface type. I do not have a separate class for the concrete implementation of the interface, and I use lambda expression to create and set the interface variable. I want the equals method of the class to take into consideration, the code, which was provided via lambda expression. Different implementations must must not return equal. Is there a way to achieve this properly? Since I did not find any links related to this requirement I am doubting whether such a practice is recommended, even if it is possible to achieve the same. What is the best thing to do?
Asked
Active
Viewed 85 times
1
-
Looks like (functional) interface equality is computed as object equality, i.e. reference equality, so you may have a hard time comparing those unless you re-assign the same anonymous implementation to the field for equal classes. – Mena Mar 21 '18 at 11:37
-
@Mena The anonymous implementation works on a String which is dynamically provided. Having to pass the same implementation will require some bookkeeping. Before that I just wanted to check if there is something to achieve the same. – kishore Mar 21 '18 at 11:41
-
I passed the same implementation where equality is required to achieve equality. I don't think there is any other way around this. – kishore Apr 02 '18 at 07:31
-
One (unsatisfactory) way is to use the lambda-expression twice, once directly in the code for the definition and once in quotation-marks, saved as an extra member (or as the toString() return value of that function). Then you can check in the equals method at least if the String-representation is equal, or you can put arbitrarily much effort into normalizing the String-representation, such that even some functions are recognized as equal whose lambda expression differed by such normalization steps only. – Sebastian Aug 20 '21 at 21:32
-
1BTW, there is a similar question with a likewise discouraging answer [here](https://stackoverflow.com/questions/46912790/java-hashcode-and-equals-for-java-8-functional-interface-objects) – Sebastian Aug 20 '21 at 21:33