How do you override the equals operator so that yo...
# announcements
s
How do you override the equals operator so that you can apply it to sibling classes? I always get Operator '==' cannot be applied to 'Length.Kilometer' and 'Length.Meter' in the below example. Kotlin Playground: https://pl.kotl.in/uT4Ch5mem
Copy code
abstract class Length {
    abstract val meters: Double

    override fun equals(other: Any?): Boolean {
        if (this === other) return true
        if (other !is Length) return false
        return meters.equals(other.meters)
    }

    override fun hashCode() = meters.hashCode()

    class Meter(value: Double) : Length() {
        override val meters: Double = value
    }

    class Kilometer(value: Double) : Length() {
        override val meters: Double = value * 1000.0
    }
}

fun main() {
    val oneKm = Length.Kilometer(1.0)
    val oneThousandMeters = Length.Meter(1000.0)

    println(oneKm.equals(oneThousandMeters))
    // true

    println(oneKm as Length == oneThousandMeters as Length)
    // true

    println(oneKm == oneThousandMeters)
    // this will not compile: Operator '==' cannot be applied to 'Length.Kilometer' and 'Length.Meter'
}
k
I think you should use equals method directly
h
I think https://youtrack.jetbrains.com/issue/KT-4071 is about this – it's just a design choice Kotlin took.
s
Thanks! I did not know about this inconsistency. I thought I was doing something wrong. I'll just use the equals method like Jakub suggested.