我一直在寻找一个合适的解决方案。
我想要做的是在init方法中将特定数量的空对象添加到列表中。
abstract class TypedMaxLengthMutableList<T>() : MutableList<T> {
protected val innerList = mutableListOf<T>()
protected val maxSize = 4
init {
for (i in 1..maxSize)
this.innerList.add(???)
}
... method overrides for MutableList
}
我读过关于变体,不变量,协变量,类型,类等的信息......
但到目前为止,我还没有能够解决这个问题。
有人可以帮助我吗?
答案 0 :(得分:2)
您无法直接调用T的构造函数,因为在JVM上运行时会擦除泛型;编译后的代码将没有T在TypedMaxLengthMutableList的每个特定实例中引用的概念。
要解决此问题,您有以下选择:
() -> T
)实例的lambda,并为您要添加的每个元素调用它Class
或KClass
实例,并通过反射调用其无参数构造函数。答案 1 :(得分:0)
我看到的问题是任何类型T
都没有任何空对象。
你可以通过这个&#34;默认&#34; object作为参数:
abstract class TypedMaxLengthMutableList<T>(default: T) : MutableList<T> {
protected val innerList = mutableListOf<T>()
protected val maxSize = 4
init {
repeat(maxSize) {
this.innerList.add(default)
}
}
... method overrides for MutableList
}