【问题标题】:Access the set of abstract properties on sealed sub classes (in kotlin)访问密封子类的抽象属性集(在 kotlin 中)
【发布时间】:2019-09-11 15:42:51
【问题描述】:

我遇到了一种情况,我有一个必须在密封类的每个子类上定义的公共属性。 我希望能够访问这些值的集合/列表而无需“复制”列表(通过硬编码) 希望下面的代码能表达我的意思

    sealed class S {
        companion object {
            // want to avoid typing: listOf("these", "values", please")
            // instead grab it from the classes themselves
            val properties = S::class.sealedSubclasses.map { /* What to do here? */ }
        }

        abstract val property: String
    }

    class A(val d: String) : S() {
        override val property: String = "these"
    }
    class B(val e: String) : S() {
        override val property: String = "values"
    }
    class C(val f: String) : S() {
        override val property: String = "please"
    }

我知道来自 kotlin.reflect.full 的 fun <T : Any> KClass<T>.createInstance(): T,但我的构造函数有非可选参数。

【问题讨论】:

  • 你的属性不是静态的,所以它的值取决于实例。

标签: kotlin companion-object sealed-class


【解决方案1】:

您可以为此创建一个createInstance(vararg) 扩展函数:

fun <T : Any> KClass<T>.createInstance(vararg args: Any): T =
  java.constructors.first().newInstance(*args) as T

S::class.sealedSubclasses.map { it.createInstance("the string") }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-03
    • 2019-05-15
    • 1970-01-01
    • 1970-01-01
    • 2011-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多