10

I have a class

open class Texture 

and I'd like to define the equals(other: Texture) operator

operator fun equals(other: Texture) = ...

but I get

Error:(129, 5) Kotlin: 'operator' modifier is inapplicable on this function: must override ''equals()'' in Any

What does it mean?

If I change that to

operator fun equals(other: Any) = ...

Accidental override, two declarations have the same jvm signature

1 Answer 1

9

The equals() operator function is defined in Any, so it should be overriden with a compatible signature: its parameter other should be of type Any?, and its return value should be Boolean or its subtype (it's final):

open class Texture { // ... override operator fun equals(other: Any?): Boolean { ... } } 

Without the override modifier, your function will clash with the Any::equals, hence the accidental override. Also, equals() cannot be an extension (just like toString()), and it cannot be overriden in an interface.

In IntelliJ IDEA, you can use Ctrl+O to override a member, or Ctrl+Insert to generate equals()+hashCode()

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

3 Comments

Updated the answer due to the update of the question.
How do you arrange for the function to return false when other is not an instance of Texture?
@saulspatz: I guess the first line lines could be if (other == null || other !is Texture) return false

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.