通过地图进行属性委派以获取开放层次结构

时间:2018-11-21 11:08:43

标签: kotlin delegates immutability

考虑到我有一个开放式层次结构的基础,其中所有属性都delegated到一个地图:

interface JsonExternalizable {
    fun serialize(): MutableMap<String, JsonNode>
}

abstract class AbstractJsonExternalizable protected constructor(private val map: Map<String, Any?>) : JsonExternalizable {
    override fun serialize(): MutableMap<String, JsonNode> {
        // ...
    }
}

现在有一个示例不可变实现(我想要一个附加的辅助构造函数,其中参数列表将“镜像”该类型的相应属性):

open class Bean1 protected constructor(map: Map<String, Any?>) : AbstractJsonExternalizable(map) {
    constructor(property1: String,
                property2: Int,
                property3: Boolean) : this(mapOf(Bean1::property1 to property1,
                                                 Bean1::property2 to property2,
                                                 Bean1::property3 to property3).mapKeys { it.key.name })

    val property1: String by map
    val property2: Int by map
    val property3: Boolean by map
}

对于更多“远距离”后代来说情况变得更糟,因为我必须在辅助构造函数中列出每个超类型属性(以及自己的属性):

class Bean3 private constructor(map: Map<String, Any?>) : Bean1(map) {
    val propertyX: Array<Byte> by map

    constructor(property1: String,
                property2: Int,
                property3: Boolean,
                propertyX: Array<Byte>) : this(mapOf(Bean3::property1 to property1,
                                                     Bean3::property2 to property2,
                                                     Bean3::property3 to property3,
                                                     Bean3::propertyX to propertyX).mapKeys { it.key.name })
}

有更少的样板代码来表达相同想法的更优雅的方式吗?

0 个答案:

没有答案