Home > front end >  Does kotlin's compareTo function support generics or Am I doing something wrong?
Does kotlin's compareTo function support generics or Am I doing something wrong?

Time:09-17

I want two Point objects to be compared without using equals, using compareTo like this:


    class  Point<T: Number>(val x: T, val y: T): Comparable<Point<T>>{
        override fun compareTo(other: Point<T>): Int {
            return compareValuesBy(this, other) {
                it<T>.x; it<T>.y
            }}
        }

Without the generic T, the code compiles. What's wrong with this code?

CodePudding user response:

The compiler doesn't know T is Comparable. You want

class  Point<T>(val x: T, val y: T): Comparable<Point<T>> where T: Number, T : Comparable<T> {
    override fun compareTo(other: Point<T>): Int {
        return compareValuesBy(this, other) {
            it.x; it.y
        }
    }
}
  • Related