Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort unbound Comparable in Scala

I am somewhat familiar with sorting in Scala using Ordering's, however I would like to sort some objects which are defined in Java. They are Comparable (not Comparable[T]) and final:

final class Term implements Comparable { ... }

(this is actually Lucene's Term class, and no I can't change the version of Lucene).

I first hoped there was an implicit somewhere:

terms.sorted //fail - no implicit ordering

So maybe I could make it ordered?

class OrderedTerm extends Term with Ordering[Term] //fail - class is final

After this I thought I'd resort to the nastiness of using java.util.Collections.sort:

Collections.sort(terms) // error: inferred type arguments [org.apache.lucene.index.Term] do not conform to method sort's type parameter bounds [T <: java.lang.Comparable[_ >: T]]

So it seems even this doesn't work as Scala is strict with it's type parameters. At this point I can see two ways to go: reimplement another explicit ordering (bad) or write the sort in Java (not quite as bad).

Is there some way to do this cleanly in Scala? I assume that this situation may be common using legacy Java objects?

like image 816
jpg Avatar asked Feb 23 '23 12:02

jpg


1 Answers

Ordering (as opposed to Ordered) is separate from the compared type. It is equivalent to java Comparator, not Comparable. So you simply define you ordering on Terms as a singleton, there is no problem with inheriting Term.

implicit object TermOrdering extends Ordering[Term] {
  def compare(t1: Term, t2: Term: Term): Int = ....
}

Better mark it implicit because it will be convenient to have it in implicit scope. Then you just have to ensure that TermOdering is imported when you call some operation that needs it.

P.S. You should read this great answer by Daniel Sobral.

like image 78
Didier Dupont Avatar answered Feb 25 '23 02:02

Didier Dupont