Sort unbound Comparable in Scala

假如想象 提交于 2019-12-10 15:26:39

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/8006195/sort-unbound-comparable-in-scala

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!