Search code examples
javascalaprogramming-languagesinteropcomparison

How to convert a class implementing java.lang.Comparable to implement Scala.Ordered?


Is renaming extends Comparable[A] to extends Ordered[A] and renaming def compareTo to def compare enough or is there anything I should take care of?


Solution

  • You're correct, that's all you need to do. The other methods in Ordered will use their default implementations, which go as follows:

    def <  (that: A): Boolean = (this compare that) <  0
    def >  (that: A): Boolean = (this compare that) >  0
    def <= (that: A): Boolean = (this compare that) <= 0
    def >= (that: A): Boolean = (this compare that) >= 0
    def compareTo(that: A): Int = compare(that)
    

    The only thing that doesn't have a default implementation in Ordered is compare, which you'll be defining using your old compareTo method. Should work, provided the above is what you want for your other comparisons.