我遇到了一种情况,我有一个必须在密封类的每个子类上定义的公共属性。我希望能够访问这些值的集合/列表而无需“复制”列表(通过硬编码)希望下面的代码传达我的意思
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"
}
我fun <T : Any> KClass<T>.createInstance(): T
从 kotlin.reflect.full 了解到,但我的构造函数有非可选参数。