kotlin - 子类的 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 可用的反射来覆盖每个未来子类的工厂时如何使这项工作的任何想法?
解决方案
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)"
}
推荐阅读
- reactjs - 如何从我的 npm 包中的 react 项目中读取文件?
- python - if 语句加上 concat 结果 pandas
- excel - 应用程序定义或对象定义 End(xlDown) 错误
- html - HTML 页脚背景不适合页脚文本
- angular - ionic 5 angular(电容器相机)和nodejs multer中的多张图像上传
- c++ - 即使没有错误,也不会注入 dll 库
- json - 如何在飞镖颤动中将嵌套的json字符串转换为json对象?
- node.js - 我们不能 SEO Mern Stack 应用程序和 reactjs 应用程序吗?
- javascript - 如何检查对象数组是否具有相同键的相同值?
- algorithm - 当内存资源有限时,哪种技术更可取迭代或递归?