簡體   English   中英

在Delegates.observable中使用propertyName參數

[英]Use of propertyName parameter in Delegates.observable

Kotlin中Delegates.observable的語法包括“ propertyName,oldValue和newValue”。

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

但是,當我嘗試對一組屬性重用相同的可觀察值時,它將無法正常工作。

例如

 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

令我困惑的是,如果我們不能為不同的屬性重用Observable委托,那么為什么它包含屬性名呢? 有什么特別的原因嗎?

為什么不關注:

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

為什么說它不起作用?

這段代碼:

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"
}

輸出此:

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

考慮到namename1name2本質上是同一字段的別名,這對我來說似乎很好-這是相同的情況,就像您為mutiple屬性使用相同的后備字段一樣。

至於為什么將屬性名稱分配給委托人-您還如何知道使用哪個屬性來訪問該字段? 同樣在您的第一個示例中,如果您更改屬性名稱,則委托仍會打印正確的消息。 但是在第二篇文章中,如果更改屬性名稱以使suer消息保持正確,則需要記住更新委托。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM