Hm, that’s weird. I wonder why Kotlin allows a dir...
# announcements
r
Hm, that’s weird. I wonder why Kotlin allows a direct
.equals()
call, but not a
==
call
a
There can only be one
equals()
per class, how would you implement it with sealed classes?
b
That’s because
==
only works on the
equals
operator. You can’t overload it, but rather only override it (from
Any
).
Copy code
override fun equals(other: Any?): Boolean {
    return if (other is Color) {
        name == other.name
    } else if (other is String) {
        name == other
    } else {
        super.equals(other)
    }
}
but just be sure to fulfill the
hashCode
contract as well
Copy code
override fun hashCode(): Int = name.hashCode()
Note that the
==
operator in Kotlin code is translated into a call to [equals] when objects on both sides of the operator are not null.