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
}
}
}