I want to have a base interface A that requires all subclasses implement A have equals method that compare only the id property, which is like this:
interface A{
val id:Int
override fun equals(that:Any?):Boolean{//error: An interface may not implement a method of 'Any'
if(that !is A) return false
else return this.id == that.id
}
}
But an error An interface may not implement a method of 'Any' appears.
If an interface is not allowed to override equals, then how could you restrict that subclasses compare only the id property?
BTW. A is required to be an interface, because subclasses may extends other classes.
That’s only possible for abstract classes. Even if interfaces could override equals, there would be no way to make that implementation final, ie classes could always override it.
What do you think should happen if multiple interfaces define each an implementation of equals and you implement all of them? Stuff like this is complicated.
@Jonathan.Haas
Currently I only manage to write override fun equals(that:Any?):Boolean without implementation to require all subclasses to implement equals and all of them uses the same equals code.
Then you throw an error, and require that the subclasser implement the method itself, possibly delegating to a superclass. Also, it’s not like this is only possible for methods on Any: this can happen with any method. It can even happen without implementations, if there are conflicting return types.