昨天介紹了委任以及覆寫成員的特性
今天則要繼續深入介紹委任的性質
如下範例
當我們試著從p去讀取時,由於委任性質的緣故
來自Delegate的getValue()函式會被呼叫
並印出以下字串Example@33a17727, thank you for delegating 'p' to me!
class Example {
var p: String by Delegate()
}
import kotlin.reflect.KProperty
class Delegate {
operator fun getValue(thisRef: Any?, property: KProperty<*>): String {
return "$thisRef, thank you for delegating '${property.name}' to me!"
}
operator fun setValue(thisRef: Any?, property: KProperty<*>, value: String) {
println("$value has been assigned to '${property.name}' in $thisRef.")
}
}