为什么Ordered[A]使用compare方法而不是重用compareTo?
trait Ordered[A] extends java.lang.Comparable[A] {
def compare(that: A): Int
def < (that: A): Boolean = (this compare that) < 0
def > (that: A): Boolean = (this compare that) > 0
def <= (that: A): Boolean = (this compare that) <= 0
def >= (that: A): Boolean = (this compare that) >= 0
def compareTo(that: A): Int = compare(that)
}
同时拥有 compare
和 compareTo
是不是有点没用? 我在这里缺少的巨大好处是什么?
如果他们刚刚使用了 compareTo
,我只需在代码中将 Comparable
替换为 Ordered
就可以了。
trait Ordered[A] extends java.lang.Comparable[A] {
def compare(that: A): Int
def < (that: A): Boolean = (this compare that) < 0
def > (that: A): Boolean = (this compare that) > 0
def <= (that: A): Boolean = (this compare that) <= 0
def >= (that: A): Boolean = (this compare that) >= 0
def compareTo(that: A): Int = compare(that)
}
Isn't it a bit useless to have both compare
and compareTo
?
What is the huge benefit I'm missing here?
If they had just used compareTo
I could just had replaced Comparable
with Ordered
in my code and be done.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为这是一次历史性事故。
Ordered
最初并不是继承自Comparable
。一旦完成,compare
名称就已经建立了。I think it's a historic accident.
Ordered
originally did not inherit fromComparable
. Once it did, thecompare
name was already established.我假设 Scala 库的作者更喜欢compare()这个名字。
I assume the authors of the Scala libraries just prefer the name compare().