在Scala中对未绑定可比对象进行排序 [英] Sort unbound Comparable in Scala

查看:88
本文介绍了在Scala中对未绑定可比对象进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有点熟悉使用 Ordering 在Scala中进行排序,但是我想对Java中定义的一些对象进行排序。它们是可比较(不是可比较[T] )和最终

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 { ... }

(这实际上是Lucene的Term类,不,我不能更改Lucene的版本)。

(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

在此之后,我以为我会使用 java.util.Collections.sort 的麻烦:

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]]

因为Scala的类型参数很严格,所以它是k。此时,我可以看到两种方法:重新实现另一个显式排序(错误)或用Java编写排序(不那么糟糕)。

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).

是否有某种方法在Scala中干净地做到这一点?我以为使用旧版Java对象可能会遇到这种情况?

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

推荐答案

订购(而不是 Ordered )与比较类型分开。它等效于Java Comparator ,而不是 Comparable 。因此,您只需将您在条款上的订购定义为单例,就可以继承 Term

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 = ....
}

最好将其标记为隐式,因为将其包含在隐式范围内会很方便。然后,您只需要确保在调用需要该操作的某些操作时导入 TermOdering

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。您应该阅读Daniel Sobral撰写的出色的 answer

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

这篇关于在Scala中对未绑定可比对象进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆