首页 > 解决方案 > 子类的 kotlin 工厂

问题描述

我有一个需要一个工厂的类,当提供一个子类的样本值时,它将用子类的类创建一个新对象。例如

open class Base(val i:Int){
    fun <T:Base>factory(sample:T, n:Int) = Base(i) // need sample." invoke constructor" (i) as T
}

关于如何在使用 Base 的任何子类作为 aa 参数调用而不需要添加样板或反射超出 KotlinJS 可用的反射来覆盖每个未来子类的工厂时如何使这项工作的任何想法?

标签: kotlinconstructorannotationsfactory

解决方案


open class Base(val i: Int) {

    fun <T : Base> factory(sample: T, @Suppress("UNUSED_PARAMETER") n: Int): Base {
        @Suppress("UNUSED_VARIABLE") val constructor = sample::class.js

        return js("new constructor(n)") as Base
    }

    override fun toString() = "Base($i)"
}

class Derived(i: Int) : Base(i) {

    override fun toString() = "Derived($i)"
}


fun main() {
    println(Base(10).factory(Derived(20), n = 5))  // "Derived(5)"
}

推荐阅读