Compare on superclasses


#1

I have some tuple-like container class that consists of an element A (which can be either of type B or C) and a something else, maybe a number in the middle (not used).

I want to order the container class so need to have a compare method like the one below.

In this compare method, I compare elements of type A (first elem1 and then elem3). However, I get stuck when trying to implement this. A simple example below says that compare method on type A is not defined. I never need to compare type A’s other than in the compare method of Container.

Please could you let me know the (typing?) problem. Sometimes it errors saying the parameter types of the subclass and traits need to match.

case class Container(elem1: A, elem2: Int, elem3:A) extends Ordered[Container]{
  def compare(that: Container): Int = elem1.compare(that.elem1) match {
    case 0 => elem3.compare(that.elem3)
    case something => something
  }
}

abstract class??? or maybe trait??? A extends Ordered[A]

class B(val n: Int) extends A {
  def compare(that: B): Int = n - that.n      // not interesting just for example
}

class C(val str: String) extends A {
  def compare(that: String) = 0                // ditto
}

#2

In your example, the compare methods take B and String, respectively, but they all need to take A, even if implemented in B or C, to match the compare method of Ordered[A].

**class B(val n: Int) extends A {
def compare(that: A): Int = n - that.n // not interesting just for example
}

class C(val str: String) extends A {
def compare(that: A) = 0 // ditto
}**


#3

Why can’t A be a fixed class?

Otherwise how do we handle:

Container(1,2,3).compareTo(Container("1",2,"3")