简体   繁体   中英

Use of propertyName parameter in Delegates.observable

The syntax for Delegates.observable in Kotlin consist of "propertyName, oldValue , newValue".

var name: String by Delegates.observable("no name") {
        d, old, new ->
        println("$old - $new")
    }

However, when I try to reuse the same observable for bunch of properties it won't work.

eg

 private val observablePropertyDelegate 
= Delegates.observable("<none>")
     { pName, oldValue, newValue ->println("$pName is updated,$oldValue to $newValue")
            }
   var name: String by observablePropertyDelegate
   var name1: String by observablePropertyDelegate
   var name2: String  by observablePropertyDelegate

What confuses me is if we can not re-use the Observable delegates for different properties, then why does it contain the property name? Is there any particular reason?

Why not following:

private val observablePropertyDelegate 
    = Delegates.observable("myOwnProperty","<none>")
         { oldValue, newValue ->println("myOwnProperty is updated,$oldValue to $newValue")
                }

Why do you say it does not work?

This code:

import kotlin.properties.Delegates

class Test {
    private val observablePropertyDelegate
        = Delegates.observable("<none>")
    { pName, oldValue, newValue ->println("$pName is updated, $oldValue to $newValue")}

    var name: String by observablePropertyDelegate
    var name1: String by observablePropertyDelegate
    var name2: String  by observablePropertyDelegate
}

fun main(args: Array<String>) {
    val test = Test()

    test.name = "a"
    test.name1 = "b"
    test.name2 = "c"

    test.name = "d"
    test.name1 = "e"
    test.name2 = "f"
}

outputs this:

property name (Kotlin reflection is not available) is updated, <none> to a
property name1 (Kotlin reflection is not available) is updated, a to b
property name2 (Kotlin reflection is not available) is updated, b to c
property name (Kotlin reflection is not available) is updated, c to d
property name1 (Kotlin reflection is not available) is updated, d to e
property name2 (Kotlin reflection is not available) is updated, e to f

which seems fine to me considering name , name1 and name2 are essentially aliases for the same field - this is the same situation as if you used the same backing field for mutliple properties.

As for why property name is assed to the delegate - how else would you know which property was used to access the field? Also in your first example the delegate still prints correct message if you change the property name. However in the second one you need to remember to update delegate if change property name to make suer message stays correct.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM