Reputation: 5568
I have been searching for a while to get a proper solution for this.
What I would like to do is add a specific number of empty objects to a list in the init method.
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
}
I've read about variants, invariants,covariants, types, classes, etc...
But so far I haven't been able to crack this one.
Could someone help me out here?
Upvotes: 1
Views: 1696
Reputation: 97148
You can't invoke the constructor of T directly because generics are erased at runtime on the JVM; the compiled code will have no concept of what T refers to in each particular instance of TypedMaxLengthMutableList.
To solve this problem, you have the following options:
() -> T
), and invoke it for every element that you're addingClass
or KClass
instance representing the type of T and invoke its no-arg constructor through reflection.Upvotes: 2
Reputation: 33769
The problem I see is that there isn't any empty object for any type T
.
You could pass this "default" object as a parameter:
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
}
Upvotes: 0