gpt4 book ai didi

Kotlin 公案 : Operator overloading

转载 作者:行者123 更新时间:2023-12-02 08:57:12 25 4
gpt4 key购买 nike

我正在完成 Kotlin Koans 的 Comparison练习并想知道为什么 compareTo() 是被重写的函数,但 compare() 是正在使用的函数。

这两个函数有何关联?

data class MyDate(val year: Int, val month: Int, val dayOfMonth: Int) : Comparable<MyDate> {
override fun compareTo(otherDate: MyDate): Int = when {
year != otherDate.year -> year - otherDate.year
month != otherDate.month -> month - otherDate.month
else -> dayOfMonth - otherDate.dayOfMonth
}
}

fun compare(date1: MyDate, date2: MyDate) = date1 < date2

最佳答案

compare()函数那里只是一个占位符显示“如何使用compareTo()”,没有实际意义。您可以根据需要将其更改为其他名称。

How do the two functions relate here?

随机命名的函数compare()来电 MyDatecompareTo()带有比较器符号 < 的函数

关于 Kotlin 公案 : Operator overloading,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54955015/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com