https://kotlinlang.org logo
#announcements
Title
# announcements
r

rook

10/27/2017, 4:20 PM
Hm, that’s weird. I wonder why Kotlin allows a direct
.equals()
call, but not a
==
call
a

Andreas Sinz

10/27/2017, 8:35 PM
There can only be one
equals()
per class, how would you implement it with sealed classes?
b

bdawg.io

10/28/2017, 7:05 AM
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.
2 Views