Home > OS >  implement inequality symbols for a custom class in kotlin
implement inequality symbols for a custom class in kotlin

Time:01-20

I have this class:


    

class Dog<T: Comparable<T>>(private val name: T, private val weight: T): Comparable<Dog<T>> {
 override fun compareTo(other: Dog<T>): Int {
  TODO("Not yet implemented")
 }
 
 override fun equals(other: Any?): Boolean {
  return (other is Dog<*>) && (other.weight == weight)
 }
}


and I want to compare any two dogs based on their weights, not names like this:


    fun main() {
     val dog1 = Dog("Dog1", 10)
     val dog2 = Dog("Dog2", 11)
    
     println(dog1 > dog2)
     println(dog1 <= dog2)

}

I am at a loss to implement the compareTo function. I would appreciate it if you could help.

CodePudding user response:

If weight needs to be generic, you can try with this Dog class:

class Dog<T : Comparable<T>>(private val name: String, private val weight: T): Comparable<Dog<T>> {
    override fun compareTo(other: Dog<T>): Int {
        return weight.compareTo(other.weight)
    }

    override fun equals(other: Any?): Boolean {
        if (other == null || other !is Dog<*>) return false
        return name == other.name && weight == other.weight
    }
}

Just make sure your weight has compareTo() function properly implemented.

  • Related