Scala 中未绑定的可比较排序
我对 Scala 中使用 Ordering
进行排序有些熟悉,但是我想对 Java 中定义的一些对象进行排序。它们是Comparable
(不是Comparable[T]
)和final
:(
final class Term implements Comparable { ... }
这实际上是Lucene的Term类,不,我不能改变Lucene 版本)。
我首先希望有一个隐含的地方:
terms.sorted //fail - no implicit ordering
所以也许我可以让它订购?
class OrderedTerm extends Term with Ordering[Term] //fail - class is final
在此之后,我想我应该求助于使用 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 对它的类型参数非常严格。此时我可以看到两种方法:重新实现另一个显式排序(不好)或用 Java 编写排序(没那么糟糕)。
有没有办法在 Scala 中干净地做到这一点?我认为这种情况在使用遗留 Java 对象时可能很常见?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Ordering
(与Ordered
相反)与比较类型是分开的。它相当于java的Comparator
,而不是Comparable
。所以你只需将Terms上的ordering定义为单例,继承Term
就没有问题了。最好将其标记为隐式,因为将其置于隐式范围内会很方便。然后,您只需确保在调用某些需要它的操作时导入
TermOdering
即可。PS:您应该阅读 Daniel Sobral 的这篇精彩答案 。
Ordering
(as opposed toOrdered
) is separate from the compared type. It is equivalent to javaComparator
, notComparable
. So you simply define you ordering on Terms as a singleton, there is no problem with inheritingTerm
.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.