【发布时间】:2018-02-12 13:24:07
【问题描述】:
我正在进行 Kotlin Koans 测试以熟悉 Kotlin。在某个测试中,我必须重写 compareTo 方法。在第一种情况下,一切都按预期工作
data class MyDate(val year: Int, val month: Int, val dayOfMonth: Int) {
operator fun compareTo(other: MyDate)= when {
year != other.year -> year - other.year
month != other.month -> month - other.month
else -> dayOfMonth - other.dayOfMonth
}
}
现在,在第二种情况下,我编写compareTo 的方式略有不同,我得到了大量的编译错误。
data class MyDate(val year: Int, val month: Int, val dayOfMonth: Int) {
operator fun compareTo(other: MyDate){
when {
year != other.year -> return year - other.year
month != other.month -> return month - other.month
else -> return dayOfMonth - other.dayOfMonth
}
}
}
首先,在 operator 关键字处,我得到一个错误:
'operator'修饰符不适用于此函数:必须返回 Int
在我得到的回报中
类型不匹配:推断类型为 Int 但应为 Unit
我不明白为什么会出现这些错误,因为第一个实现返回相同的 Ints
【问题讨论】:
标签: kotlin