为什么Ordered[A]使用compare方法而不是重用compareTo?

发布于 2024-10-09 03:24:50 字数 584 浏览 0 评论 0原文

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

同时拥有 comparecompareTo 是不是有点没用? 我在这里缺少的巨大好处是什么?

如果他们刚刚使用了 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

听,心雨的声音 2024-10-16 03:24:50

我认为这是一次历史性事故。 Ordered 最初并不是继承自 Comparable。一旦完成,compare 名称就已经建立了。

I think it's a historic accident. Ordered originally did not inherit from Comparable. Once it did, the compare name was already established.

盛夏已如深秋| 2024-10-16 03:24:50

我假设 Scala 库的作者更喜欢compare()这个名字。

I assume the authors of the Scala libraries just prefer the name compare().

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文