Sort unbound Comparable in Scala

I am a little familiar with sorting in Scala using Ordering , but I would like to sort some objects defined in Java. They are Comparable (not Comparable[T] ) and final :

 final class Term implements Comparable { ... } 

(this is actually the Lucene Term class, and I cannot change the version of Lucene).

At first, I hoped there was an implicit somewhere:

 terms.sorted //fail - no implicit ordering 

So maybe I could order it?

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

After that, I thought I would 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 type parameter bounds [T <: java.lang.Comparable[_ >: T]] 

So, it seems that even this does not work, since Scala is strict with type parameters. At this point, I see two ways: override another explicit ordering (bad) or write sorting in Java (not really like that).

Is there a way to do this cleanly in Scala? I assume this situation could be spread using legacy Java objects?

+4
source share
1 answer

Ordering (unlike Ordered ) is separate from the type being compared. This is equivalent to java Comparator , not Comparable . Thus, you simply determine what you order under the Conditions as a singleton, there are no problems with the inheritance of Term .

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

It is better to mark it implicitly, because it will be convenient to have it in the implicit area. Then you just need to make sure that TermOdering imported when you invoke some operation that it needs.

PS You should read this excellent answer by Daniel Sobral.

+8
source

Source: https://habr.com/ru/post/1379600/


All Articles