属性代理
普通代理
就是属性的监听器,虽然简单,但是还是有点不理解的是,不知道怎么获取属性值。。。。。fuck!
fun BaseMain() {
var ani = Animal()
ani.x = "this"
println(ani.x)
ani.x = "112"
}
class Animal {
var x: String by Dog()
}
class Dog {
operator fun getValue(thisRef: Any?, pr: KProperty<*>): String {
return "This is property name of ${pr.name}"
}
operator fun setValue(thisRef: Any?, property: KProperty<*>, value: String) {
println("value is $value")
}
}
lazy 代理
第一次调用会将lambda表达式过一遍,以后就会直接记住返回值,和普通变量一样
fun BaseMain() {
println(lazyValue)
println(lazyValue)
println(lazyValue)
println(lazyValue)
}
val lazyValue: String by lazy {
println("computed!")
"Hello"
}
/**打印
computed!
Hello
Hello
Hello
Hello
*/
Observable
这是kotlin 内置的类Delegates ,直接用就行的了
fun BaseMain() {
var ani = Animal()
ani.name = "Dog"
ani.name = "Cat"
}
class Animal {
var name: String by Delegates.observable("init_name") { pro, old, new ->
println("the property is ${pro.name} and the old is $old,the newer is $new ")
}
}
/**
打印
the property is name and the old is init_name,the newer is Dog
the property is name and the old is Dog,the newer is Cat
*/
将值存储在map中
有点类似解析json,使用如下,你觉得爽哇
fun BaseMain() {
var room = Room(mapOf(
"x" to 1,
"y" to 2,
"z" to 3
))
println("This room is bigger you like, the x is ${room.x} and the y is ${room.y}")
}
class Room(val map: Map<String, Any?>) {
val x: Int by map
val y: Int by map
}
class MutableRoom(val map: MutableMap<String, Any?>) {
var name: String by map
var age: Int by map
}
/**
This room is bigger you like, the x is 1 and the y is 2
*/