Johan Vergeer
Johan Vergeer

Reputation: 5568

How can I add an instance of a generic type to a list in Kotlin

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

Answers (2)

yole
yole

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:

  • Pass an empty object instance as a constructor parameter, as voddan suggests;
  • Pass a lambda that creates an instance of T (() -> T), and invoke it for every element that you're adding
  • Pass a Class or KClass instance representing the type of T and invoke its no-arg constructor through reflection.

Upvotes: 2

voddan
voddan

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

Related Questions