属性代理

    1. class Delegates{
    2. val hello by lazy {
    3. "HelloWorld"
    4. }
    5. val hello2 by X()
    6. var hello3 by X()
    7. }
    8. class X{
    9. private var value: String? = null
    10. operator fun getValue(thisRef: Any?, property: KProperty<*>): String {
    11. println("getValue: $thisRef -> ${property.name}")
    12. return value?: ""
    13. }
    14. operator fun setValue(thisRef: Any?, property: KProperty<*>, value: String){
    15. println("setValue, $thisRef -> ${property.name} = $value")
    16. this.value = value
    17. }
    18. }
    19. fun main(args: Array<String>) {
    20. val delegates = Delegates()
    21. println(delegates.hello)
    22. println(delegates.hello2)
    23. println(delegates.hello3)
    24. delegates.hello3 = "value of hello3"
    25. println(delegates.hello3)
    26. }