I have five subclasses of Z, namely A…E and I want to impose an order on them such that A<B<C<D<E. I previously made Z extend Ordered but answers in this group encourage me to use an implicit Ordering[Z]
and using typeclasses.
Currently, with my Z extends Ordered[Z]
, I have a compare method for every subclass that states how the order should be realised, e.g.:
class C extends Z {
def compare(other: Z) = {
other match {
case _ : A => +1
case _ : B => +1
case that: C => this.field compare that.field
case _ : D => -1
case _ : E => -1
}
}
Now, if I wanted to change the ordering such that D < E < B < A < C, I would have to go into every subclass and make sure everything was consistent again, which could introduce errors.
In the typeclass way of doing things, where you compare two items outside of any scope of a this
object, is there a trick using something like Ordering[Z].by...
so that an ordering is imposed? Or would this create a cross product case analysis where every subclass has to be compared with every other subclass? What I want to do is say all A’s are less than Bs … Zs, but if a A comes in, compare by each field in turn but express this once, rather than in every class.
Any pointers appreciated!