Properties Kotlin-如何使用自定义名称通过映射创建属性委托?

Properties Kotlin-如何使用自定义名称通过映射创建属性委托?,properties,delegates,kotlin,delegation,Properties,Delegates,Kotlin,Delegation,我正试图了解属性代理,我有一个有趣的用例。有没有可能有这样的东西: class MyClass { val properties = mutableMapOf<String, Any>() val fontSize: Any by MapDelegate(properties, "font-size") } class-MyClass{ val properties=mutableMapOf() val fontSize:MapDelegate的任意值(属性,“字体

我正试图了解属性代理,我有一个有趣的用例。有没有可能有这样的东西:

class MyClass {
    val properties = mutableMapOf<String, Any>()
    val fontSize: Any by MapDelegate(properties, "font-size")
}
class-MyClass{
val properties=mutableMapOf()
val fontSize:MapDelegate的任意值(属性,“字体大小”)
}
这将允许我使用映射作为代理存储
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")
}

我阅读了文档,但很难弄清楚我需要做什么。这一点非常清楚。谢谢我最终使用了第一个选项(没有自动转换)来支持JavaFX样式的CSS:
var fontSize:Any?按地图(属性,“-fx字体大小”)
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)
}
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)]
    }
}