I am trying to define an abstract class that has operators to compare two instances of the class. When concretizing the class, however, I want the methods to only compare instances of the same type. Something like this
abstract class ComparableSuper{
def <(other: ComparableSuper): Boolean
def <=(other: ComparableSuper): Boolean
def >(other: ComparableSuper): Boolean
def >=(other: ComparableSuper): Boolean
}
class Comparable (val a: Int) extends ComparableSuper {
def <(other: Comparable): Boolean = this.a < other.a
def >(other: Comparable): Boolean = this.a > other.a
def <=(other: Comparable): Boolean = this.a <= other.a
def >=(other: Comparable): Boolean = this.a >= other.a
}
Of course this code does not compile because I am not overriding the methods in the abstract class. If I change Comparable to ComparableSuper in the methods, however, I won’t have the assurance that the field a is there.
Is there a way I could specify the type of the class in the method signature?
Thanks in advance.
I highly recommend you to look at Ordering type class.
I find, that type-class approach to this problem is much better than
Comaprableway of doing it (where objects, that you want to compare, actually extendComparable).With type-class approach you will also give you more type-safety and flexibility. You can actually define
Orderinginstances for existing classes (classes that you can’t control and change).Orderingcan be a little bit clumsy to use, butOrderedhas implicits that will allow you to write code like this:So you even don’t compromise convenience. (by the way,
Orderedis equivalent to Java’sComparable)