簡體   English   中英

Kotlin - 如何通過地圖使用自定義名稱進行屬性委托?

[英]Kotlin - How to make a property delegate by map with a custom name?

我試圖讓我的頭腦周圍的財產代表,我有一個有趣的用例。 有可能有這樣的事情:

class MyClass {
    val properties = mutableMapOf<String, Any>()
    val fontSize: Any by MapDelegate(properties, "font-size")
}

這將允許我使用地圖作為委托存儲fontSize ,但使用自定義鍵(即“font-size”)。

具體用例如果用於存儲CSS屬性標簽之類的東西,可以通過變量( fontSize )訪問以便在代碼中使用,但可以在迭代地圖時正確呈現( font-size: 18px; )。

委托屬性的文檔是有關該主題的良好信息來源。 它可能比以下示例讀取時間長一些:

fun <T, TValue> T.map(properties: MutableMap<String, TValue>, key: String): ReadOnlyProperty<T, TValue> {
    return object : ReadOnlyProperty<T, TValue> {
        override fun getValue(thisRef: T, property: KProperty<*>) = properties[key]!!
    }
}

class MyClass {
    val properties = mutableMapOf<String, Any>()
    val fontSize: Any by map(properties, "font-size")
}

您可以稍微簡化一下,避免鍵入CSS屬性名稱,方法是將Kotlin屬性名稱轉換為CSS屬性等價物,如下所示:

fun <T, TValue> map(properties: Map<String, TValue>, naming:(String)->String): ReadOnlyProperty<T, TValue?> {
    return object : ReadOnlyProperty<T, TValue?> {
        override fun getValue(thisRef: T, property: KProperty<*>) = properties[naming(property.name)]
    }
}

object CamelToHyphen : (String)->String {
    override fun invoke(camelCase: String): String {
        return CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_HYPHEN, camelCase)
    }
}

fun <T, TValue> T.cssProperties(properties: Map<String,TValue>) = map(properties, CamelToHyphen)

class MyClass {
    val properties = mutableMapOf<String, Any>()
    val fontSize: Any? by cssProperties(properties)
}

上面的示例使用了Guava的CaseFormat

如果您想擁有可變屬性,您的委托必須實現setter方法:

fun <T, TValue> map(properties: MutableMap<String, TValue?>, naming: (String) -> String): ReadWriteProperty<T, TValue?> {
    return object : ReadWriteProperty<T, TValue?> {
        override fun setValue(thisRef: T, property: KProperty<*>, value: TValue?) {
            properties[naming(property.name)] = value
        }

        override fun getValue(thisRef: T, property: KProperty<*>) = properties[naming(property.name)]
    }
}

暫無
暫無

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

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