本節熟悉屬性和委託屬性
32. n32Properties
在Kotlin
中,類不允許擁有欄位,但是給了我們field
關鍵字實現相同的功能
class PropertyExample() {
var counter = 0
var propertyWithCounter: Int? = 0
set(value) {
field = value
counter++
}
get
}複製程式碼
33. n33LazyProperty
懶載入
class LazyProperty(val initializer: () -> Int) {
var value: Int? = null
val lazy:Int
get() {
if (value==null){
value = initializer()
}
return value!!
}
}複製程式碼
initializer
是一個lambda
表示式,這個表示式會在lazy
屬性第一次被訪問的時候執行,且僅執行一次
34. n34DelegatesExamples
用委託實現懶載入
class LazyPropertyUsingDelegates(val initializer: () -> Int) {
val lazyValue: Int by lazy(initializer)
}複製程式碼
35. n35HowDelegatesWork
該練習幫我們瞭解委託如何工作,D
類把date
屬性的set
和get
方法委託給EffectiveDate
class EffectiveDate<R> : ReadWriteProperty<R, MyDate> {
var timeInMillis: Long? = null
operator override fun getValue(thisRef: R, property: KProperty<*>): MyDate = timeInMillis!!.toDate()
operator override fun setValue(thisRef: R, property: KProperty<*>, value: MyDate) {
timeInMillis = value.toMillis()
}
}複製程式碼