gpt4 book ai didi

properties - Kotlin - 如何使用自定义名称通过 map 制作属性委托(delegate)?

转载 作者:行者123 更新时间:2023-12-03 13:03:24 25 4
gpt4 key购买 nike

我正在尝试了解属性委托(delegate),并且我有一个有趣的用例。有没有可能有这样的东西:

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

这将允许我使用 map 作为委托(delegate)来存储 fontSize,但使用自定义键(即“font-size”)。

特定用例用于存储诸如 CSS 属性标签之类的内容,这些内容可以通过变量 (fontSize) 访问以在代码中使用,但在遍历 map 时可以正确呈现 (字体大小:18px;).

最佳答案

关于 the delegated properties 的文档是有关该主题的良好信息来源。读起来可能比下面的例子要长一点:

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

您可以通过将 Kotlin 属性名称转换为等效的 CSS 属性名称来简化操作,避免键入 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 .

如果你想拥有可变属性,你的委托(delegate)必须实现 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)]
}
}

关于properties - Kotlin - 如何使用自定义名称通过 map 制作属性委托(delegate)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36602379/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com