刚刚学习定义一个 DateRange 类型
val wholeYear2017 = Date(2017,1,1)..Date(2017,12,31)
所以我创建了如下类型
class DateRange<Date: Comparable<Date>>(override val start: Date, override val endInclusive: Date)
: ClosedRange<Date>
class Date (val year: Int, val month: Int, val day: Int) {
operator fun compareTo(other: Date): Int {
if (this.year > other.year) return 1
if (this.year < other.year) return -1
if (this.month > other.month) return 1
if (this.month < other.month) return -1
if (this.day > other.day) return 1
if (this.day < other.day) return -1
return 0
}
operator fun rangeTo(that: Date): DateRange = DateRange(this, that)
}
但是我得到一个编译错误
One type of argument expected for class DateRange<Date: Comparable<Date>> : ClosedRange<Date>
我错过了什么?我做对了吗?
最佳答案
你需要实现Comparable
接口(interface)。您可以使用 compareValuesBy
辅助函数:
data class Data(
val a: Int,
val b: Int
) : Comparable<Data> {
override fun compareTo(other: Data) = compareValuesBy(this, other,
{ it.a },
{ it.b }
)
}
关于kotlin - 如何制作 Kotlin 可比类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46484879/