只是学习定义DateRange类型
onCreate
所以我创建了如下所示的类型
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)
}
我错过了什么?我做得对吗?
答案 0 :(得分:11)
您的问题真的是关于如何创建可比较类型吗?然后让你的类型实现Comparable接口(覆盖let shareActivity = UIActivityViewController(activityItems: ["http://www.dwz.cn/BabySmarter 我的宝宝比\(String(describing: Int(finalScore!)))% 的宝宝更发展!你的呢?"], applicationActivities: nil)
shareActivity.popoverPresentationController?.sourceView = self.view
self.present(shareActivity, animated: true, completion: nil)
)。
compareTo
您不需要class Date(val year: Int, val month: Int, val day: Int) : Comparable<Date> {
override 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
}
}
方法,因为所有rangeTo
类型都已定义Comparable<T>
个扩展名。请参阅Ranges和rangeTo。但是,如果您仍然需要自己的rangeTo
类型(用于其他目的),DateRange
类的更简单形式将是......
DateRange
换句话说,class DateRange(override val start: Date, override val endInclusive: Date)
: ClosedRange<Date>
上不需要通用参数。
然后你会编写自己的DateRange
运算符。或者,将rangeTo
添加到operator fun rangeTo
类,或者提供根级别扩展功能(我的偏好与Kotlin库方法一致)。两者都会隐藏/隐藏Date
类型的Comparable<T>.rangeTo
扩展功能。
Date
答案 1 :(得分:6)
您需要实现Comparable
接口。您可以使用compareValuesBy
辅助函数:
data class Data(
val a: Int,
val b: Int
) : Comparable<Data> {
override fun compareTo(other: Data) = compareValuesBy(this, other,
{ it.a },
{ it.b }
)
}
答案 2 :(得分:4)
你快到了:
首先,您必须制作课程Comparable
:
class Date (val year: Int, val month: Int, val day: Int): Comparable<Date> {
其次,你必须指定返回类型的泛型或者只是省略它(让编译器推断它)
operator fun rangeTo(that: Date): DateRange<Date> = DateRange(this, that)
operator fun rangeTo(that: Date) = DateRange(this, that)
答案 3 :(得分:0)
直接来自Koans。我真的鼓励您先了解文档。
override fun compareTo(other: Date) = when {
year != other.year -> year - other.year
month != other.month -> month - other.month
else -> day - other.day
}