Ori Marko
Ori Marko

Reputation: 58882

Why lombok adding canEqual method

When using lombok @Data (which adds EqualsAndHashCode)

It adds canEqual method

protected boolean canEqual(Object other) {
  return other instanceof Exercise;
}

which is only called once:

if (!other.canEqual((Object)this)) return false;

I search and found discussions about access level

If you implement equals and hashCode in a non-final class the safest thing we can do is add the can equal the way we do. Since we don't add any field the costs, especially if the method is protected, are slim.

But why do we need this generated method ? can't it be inline?

Upvotes: 21

Views: 7818

Answers (1)

cassiomolin
cassiomolin

Reputation: 131137

The canEqual method is defined in a paper entitled How to Write an Equality Method in Java. This method is meant for allowing to redefine equality on several levels of the class hierarchy while keeping its contract:

The idea is that as soon as a class redefines equals (and hashCode), it should also explicitly state that objects of this class are never equal to objects of some superclass that implement a different equality method. This is achieved by adding a method canEqual to every class that redefines equals.


Seems like it was introduced in Lombok 0.10, as described in the @EqualsAndHashCode documentation:

NEW in Lombok 0.10: Unless your class is final and extends java.lang.Object, lombok generates a canEqual method which means JPA proxies can still be equal to their base class, but subclasses that add new state don't break the equals contract.

And the documentation goes a bit further, referencing the paper quoted above:

The complicated reasons for why such a method is necessary are explained in this paper: How to Write an Equality Method in Java. If all classes in a hierarchy are a mix of scala case classes and classes with lombok-generated equals methods, all equality will 'just work'. If you need to write your own equals methods, you should always override canEqual if you change equals and hashCode.

Upvotes: 12

Related Questions