Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problems defining equals() operator

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

like image 203
elect Avatar asked Oct 29 '16 17:10

elect


People also ask

How to equal number in C++ with operator overloading?

Equal number C++ Program with operator overloading. cout<<"Please enter 1st number. "; cout<<" Please enter 1st number."; cout<<"n1 is equal to n2. "; cout<<"n1 is not equal to n2. "; Please enter 1st number. 77 Please enter 2nd number. 77 n1 is equal to n2.

Is it possible to check if operators already mimic equals?

It's not going to perform complex code analysis of the body of your operators to see if they already mimic Equals because, in the worst case, that could be equivalent to solving the halting problem.

What is the difference between == and equals in Java?

Another difference between the == and equals Java method is ‘==’ operator compares references of Java objects and the ‘equals’ Java method compares the objects based upon the implementation of the method. Let’s see the following sample program: As seen in the above program, the two String variables are assigned values as follows:

What happens if equals () method is not overridden?

If this equals () method is not overridden, then by default equals (Object obj) method of the closest parent class which has overridden this method is used. In this sample, we have used String objects for comparison and the String class has its own overridden implementation of the equals () method.


1 Answers

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()

like image 194
hotkey Avatar answered Sep 30 '22 20:09

hotkey