I was trying to overload compareTo
and equals
operators for my class.
There is no problem with compare operator. It works well both as member and as an extension function.
The equals operator must be a member and override equals fun.
class MyClass {
companion object {
private val NUMBER: Int = 5
operator fun compareTo(value: Int) = NUMBER - value
override operator fun equals(other: Any?) =
when (other) {
is Int -> NUMBER == other
else -> throw Exception("")
}
}
}
fun test() {
if (MyClass < 10) {
//ok
}
//Operator '==' cannot be applied to 'MyClass.companion' and kotlin.Int
if (MyClass == 5) {
}
}
Edit: How to overload '==' properly?