[ Kotlin ] Property Delegate

About Property Delegate

property delegate enable you get or set a property value

by DelegateObject.getValue or DelegateObject.setValue

in this way, Delegate object can be reused in similar places

Sources
kotlin 复制代码
fun main() {
    val hello = Hello()
    hello.name = "tom"
    println(hello.name)
}

class Hello {

    var name: String by Delegate()
}

class Delegate {

    private var value = ""

    operator fun getValue(thisRef: Any, property: KProperty<*>): String {
        return "${thisRef.javaClass.simpleName}::${property.name}=${value}"
    }

    operator fun setValue(thisRef: Any, property: KProperty<*>, value: String) {
        this.value = value
    }
}
相关推荐
Kiri霧7 小时前
IntelliJ IDEA
java·ide·kotlin·intellij-idea
金銀銅鐵3 天前
Kotlin 中的默认参数在 class 文件中是如何实现的?
kotlin
xjdkxnhcoskxbco3 天前
kotlin基础【1】
java·前端·kotlin
居然是阿宋3 天前
Kotlin Flow 实战:StateFlow 和 SharedFlow 的默认值陷阱
android·开发语言·kotlin
xjdkxnhcoskxbco3 天前
kotlin基础【2】
android·开发语言·kotlin
AI大法师4 天前
Kotlin与Jetpack Compose:Android开发生态的演进与架构思考
android·kotlin
Harry技术4 天前
ArcSoft 裁剪错误修复方案
android·kotlin
说码解字4 天前
Android MediaCodec 的使用和源码实现分析
android·开发语言·kotlin