Search code examples
operator-overloadingxtend

Eclipse Xtend: Overriding equals() vs. operator_equals()


Which method should I implement in Xtend if I want to declare equality check?

AFAIK if I use '==' operator, then it gets compiled as equals() call in Java.

If so, then why would I define an operator_equals() when I can simply override equals()?

UPDATE: As @kapex pointed out it is not recommended to override '==' as it can lead to code behaving differently in Xtend and Java, sample below:

class Person {
    override equals(Object person) {
        true // We are all the same
    }

    def operator_equals(Person person) {
        false // We are all different
    }
}

Solution

  • If your goal is to change "equal to" behavior, then you should simply override equals (and hashCode).

    You would only define operator_equals if you want it to have different behavior than equals. But you generally wouldn't want that.

    If you overload the == operator, the original equals method still exist and some some code might use the operator while other code will use equals (for example Java libraries). This sounds like a good way to break something.

    It makes sense for Xtend to provide the ability to overload all operators for some odd use cases or even just for consistency, but in my opinion redefining existing operator behavior is bad practice and should be avoided. It's much safer to only overload operators that are not yet defined for a type.