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
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.
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.
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:
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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With