Problems defining the equals () operator

I have a class

open class Texture 

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

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

but i get

Error: (129, 5) Kotlin: the 'operator' modifier is not applicable to this function: should override '' equals () '' in Any

What does it mean?

If I changed it to

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

Random override, two ads have the same jvm signature

+5
source share
1 answer

The operation equals() defined in Any , so it should be redefined with a compatible signature: its other parameter must be of type Any? , and its return value should be Boolean or its subtype (final):

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

Without the override modifier, your function will collide with Any::equals , therefore, a random override will occur. In addition, equals() cannot be an extension ( just like toString() ), and it cannot be overridden in an interface.

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

+5
source

Source: https://habr.com/ru/post/1258982/


All Articles