本節練習Kotlin
中各種介面的使用
25. n25Comparison
為Mydate
類實現Comparable
介面,式其可以通過我們在Comparable
介面中定義的規則直接比較
data class MyDate(val year: Int, val month: Int, val dayOfMonth: Int) : Comparable<MyDate> {
override fun compareTo(other: MyDate): Int = when {
year != other.year -> year - other.year
month != other.month -> month - other.month
else -> dayOfMonth - other.dayOfMonth
}
}複製程式碼
26. n26InRange
為DateRange
類實現方法,判斷某個Mydate
物件是否在DateRange
的範圍中
class DateRange(val start: MyDate, val endInclusive: MyDate){
operator fun contains(item:MyDate):Boolean = start<=item&&item<=endInclusive
}複製程式碼
也可以
class DateRange(override val start: MyDate, override val endInclusive: MyDate) : ClosedRange<MyDate> {
override fun contains(item: MyDate): Boolean = start <= item && item <= endInclusive
}複製程式碼
引數前新增了override
是因為CloseRange
介面中也定義了這兩個屬性,所以我們實現該介面也就複寫了這兩個引數
27. n27RangeTo
實現rangeTo
介面,該介面的功能是返回一個從當前物件到目標物件的一個集合
operator fun MyDate.rangeTo(other: MyDate): DateRange =DateRange(this,other)複製程式碼
28. n28ForLoop
為DateRange
實現Iterable
介面
可以專門建立一個類,也可以用物件表示式
class DateRange(override val start: MyDate, override val endInclusive: MyDate) : ClosedRange<MyDate>, Iterable<MyDate> {
override fun iterator(): Iterator<MyDate> = object : Iterator<MyDate> {
var current: MyDate = start
override fun next(): MyDate {
val result = current
current = current.nextDay()
return result
}
override fun hasNext(): Boolean = current <= endInclusive
}
override fun contains(item: MyDate): Boolean = start <= item && item <= endInclusive
}複製程式碼
class DateRange(override val start: MyDate, override val endInclusive: MyDate) : ClosedRange<MyDate>, Iterable<MyDate> {
override fun iterator(): Iterator<MyDate> =DateIterator(this)
override fun contains(item: MyDate): Boolean = start <= item && item <= endInclusive
}
class DateIterator(val dateRange:DateRange) : Iterator<MyDate> {
var current: MyDate = dateRange.start
override fun next(): MyDate {
val result = current
current = current.nextDay()
return result
}
override fun hasNext(): Boolean = current <= dateRange.endInclusive
}複製程式碼
29. n29OperatorsOverloading
過載操作符,僅+
operator fun MyDate.plus(timeInterval: TimeInterval) = addTimeIntervals(timeInterval,1)複製程式碼
為TimeInterval
過載*
,呼叫時一定要TimeInterval
在前
class RepeatedTimeInterval(val ti: TimeInterval, val n: Int=1)
operator fun TimeInterval.times(number:Int) = RepeatedTimeInterval(this,number)
operator fun MyDate.plus(timeInterval: RepeatedTimeInterval) = addTimeIntervals(timeInterval.ti,timeInterval.n)複製程式碼
30. n30DestructuringDeclarations
用解構宣告解構物件
class MyDate(val year: Int, val month: Int, val dayOfMonth: Int) {
operator fun component1(): Int =year
operator fun component2(): Int =month
operator fun component3(): Int =dayOfMonth
}複製程式碼
31. n31Invoke
統計呼叫次數,這裡使用了閉包
class Invokable{
var numberOfInvocations: Int = 0
private set
operator fun invoke():Invokable {
numberOfInvocations++
return this
}
}複製程式碼