屬性代理
package com.xingzhi.ui
import kotlin.reflect.KProperty
class Example{
var p:String by Delegate() //屬性也可以使用by關(guān)鍵字委托給其他對(duì)象
}
//委托了
class Delegate{
operator fun getValue(thisRef:Any?,property:KProperty<*>):String {
return "$thisRef, 這里委托了 ${property.name} 屬性"
}
operator fun setValue(thisRef: Any?,property: KProperty<*>,value: String){
print("$thisRef 的${property.name} 屬性默認(rèn)值為 $value")
}
}
fun main(){
println(Example().p)
}
image.png
kotlin在標(biāo)準(zhǔn)庫(kù)中提供的預(yù)設(shè)行數(shù)
import kotlin.reflect.KProperty
class Example{
val p:String by lazy {"這個(gè)可以有"}//lazy為我們生成一個(gè)委托對(duì)象诉探,這樣在獲取屬性值的時(shí)候就會(huì)執(zhí)行l(wèi)azy 里面的操作了,
// 看起來效果就像延遲執(zhí)行一樣攻柠,由于只能獲取磁浇,所以所只支持val變量
}
fun main(){
println(Example().p)
}
設(shè)置觀察者
import kotlin.properties.Delegates
class Example{
var p:String by Delegates.observable("我就是這么任性"){
prop,old,new ->
println("檢測(cè)到$prop 的值發(fā)生變化但校,就值$old,->新值 :$new")
}
}
fun main(){
Example().p = "這個(gè)不可能"
}
//打印的內(nèi)容
檢測(cè)到property p (Kotlin reflection is not available) 的值發(fā)生變化,就值我就是這么任性,->新值 :這個(gè)不可能
屬性也可以直接將自己委托給另外一個(gè)屬性(可以理解為給另外一個(gè)屬性起個(gè)別名)
class Example(var a:String){
var p:String by ::a
}
fun main(){
val example = Example("什么說")
println(example.p)
}
屬性也可以被委托給一個(gè)Map來進(jìn)行存儲(chǔ)
class User(map:MutableMap<String,Any>){
var name :String by map //直接魏國(guó)給外部闖入的Map 集合
var age:Int by map //變量的只從Map中進(jìn)行存儲(chǔ)
override fun toString(): String {
return "名字: $name , 年齡 : $age"
}
}
fun main(){
val map:MutableMap<String ,Any> = mutableMapOf(
"name" to "zhiguiCai",
"age" to 30
)
val user = User(map)
println(user) //名字: zhiguiCai , 年齡 : 30
map["age"] = 12
println(user) //名字: zhiguiCai , 年齡 : 12
}
柏碼知識(shí)庫(kù) | Kotlin(一)基礎(chǔ)語法
柏碼知識(shí)庫(kù) | Kotlin(二)類與對(duì)象
柏碼知識(shí)庫(kù) | Kotlin(三)高級(jí)特性