Scala Ordering case classes implementing a trait in a list

101 Views Asked by At

I have case classes that extend a trait Token and a function that returns a list of instances created using the case class apply method with appropriate parameters.

The trait defines a property name that is overridden in each case class.

A unit test calls a method that returns a list of the case class instances and tries to assert that the resultant list is the same as an expected list. This works but the comparison between lists is order dependent and although I could change the expected list to match the order of the returned list this would make the test depend on the method implementation and that is not something I wish to do.

The solution appears to be to sort the lists on that name value defined in the trait as each instance of the case class has the same name.

I have tried several things, best results so far add the extends Ordering[Token] to the Token trait, compiles except for the list sort function where I get

No implicit Ordering defined for B

My compare function in the Token trait is

  def compare(x: Token, y: Token): Int =
    x.name.compareToIgnoreCase(y.name)

There may be a better way to ignore the order in the lists however I would like at least to understand what I am doing wrong here and get the sort working.

1

There are 1 best solutions below

0
Tim On

Do you have an implicit Ordering for Token? Something like this should work:

trait Token {
  def name: String
}

object Token {
  implicit val ord: Ordering[Token] = Ordering.by(_.name.toLowerCase)
}