Kotlin基础教程-代理属性

xiaoxiao2021-02-27  226

代理属性

实例

import kotlin.reflect.KProperty /** * Created by doctorq on 2017/6/6. * 代理属性 */ class Example { var p: String by Delegate() } 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.'") } } fun main(args: Array<String>) { val e = Example() println(e.p) e.p = "test" }

执行结果:

Example@1a6c5a9e, thank you for delegating ‘p’ to me! test has been assigned to ‘p in Example@1a6c5a9e.’

从执行结果可以看出,调用e.p的时候实际调用的是代理类的getValue()方法,而调用e.p="test"实际调用的是代理类的SetValue()方法。

标准代理

lazy

val lazyValue: String by lazy { println("computed!") "Hello" } fun main(args: Array<String>) { println(lazyValue) println("==========") println(lazyValue) }

上面使用的是lazy代理,我们知道lazy定义的方法会在第一次调用时初始化,后续调用就会沿用之前的值。所以上面代码的输出如下:

computed! Hello ========== Hello

observable

实时关注属性的变化

import kotlin.properties.Delegates class QUser { var name: String by Delegates.observable("<no name>") { prop, old, new -> println("$old -> $new") } } fun main(args: Array<String>) { val user = QUser() user.name = "first" println("==========") user.name = "second" }

执行输出:

<no name> -> first ========== first -> second

使用Map存储属性

class MyUser(val map: Map<String, Any?>) { val name: String by map val age: Int by map } fun main(args: Array<String>) { val user = MyUser(mapOf( "name" to "Doctorq", "age" to 28 )) println(user.name) println(user.age) }

MyUser类中的2个属性被代理到map中对应的键值。

转载请注明原文地址: https://www.6miu.com/read-10393.html

最新回复(0)