如何将实现 java.lang.Comparable 的类转换为实现 Scala.Ordered?

发布于 2024-10-08 19:46:55 字数 157 浏览 1 评论 0原文

extends Comparable[A] 重命名为 extends Ordered[A] 并将 defcompareTo 重命名为 defcompare 是否足够,或者有什么需要我注意的吗?

Is renaming extends Comparable[A] to extends Ordered[A] and renaming def compareTo to def compare enough or is there anything I should take care of?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

万劫不复 2024-10-15 19:46:55

你是对的,这就是你需要做的。 Ordered 中的其他方法将使用其默认实现,如下所示:

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)

Ordered 中唯一没有默认实现的是 Compare,您将使用它使用旧的 compareTo 方法进行定义。应该有效,前提是上述内容是您想要进行其他比较的内容。

You're correct, that's all you need to do. The other methods in Ordered will use their default implementations, which go as follows:

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)

The only thing that doesn't have a default implementation in Ordered is compare, which you'll be defining using your old compareTo method. Should work, provided the above is what you want for your other comparisons.

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