Interface overrides equals?


#1

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.


#2

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.


#3

I thought equals isn’t that different from a default method,which reduces the duplicated code?


#4

@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.