Synesso
Synesso

Reputation: 38978

Extension function override of `equals(Any?): Boolean`

A Java dependency defines some value classes without equals methods. They really should implement it, but they don't.

public class OrderBookEntry {

  private String price;
  private String qty;

  public String getPrice() {
    return price;
  }

  public void setPrice(String price) {
    this.price = price;
  }

  public String getQty() {
    return qty;
  }

  public void setQty(String qty) {
    this.qty = qty;
  }
}

I would like to implement equals by extension

fun OrderBookEntry.equals(other: Any?): Boolean = 
  EqualsBuilder.reflectionEquals(this, other)

but I'm given a warning that

Extension is shadowed by a member. public open fun equals(other: Any?): Boolean

and the extension method has no effect.

Can I override the equals behaviour?

Upvotes: 6

Views: 5138

Answers (1)

JB Nizet
JB Nizet

Reputation: 691715

You can't override a method using an extension function.

fun OrderBookEntry.foo(other: Any?): Boolean

is equivalent, in Java, to having a static helper method such as

public static boolean foo(OrderBookEntry fakeThis, Object other)

Extension functions are resolved statically, can't shadow a member method, and must be explicitly imported (when called from another package) in order to be available.

Upvotes: 9

Related Questions