Beder123
Beder123

Reputation: 59

Kotlin How to create a list of classes that can be instantianted dynamically

I would like to have a list of classes which could be instantiated later in the program. Something like:

val someClasses = listOf(ClassA, ClassB, ...)
for (myClass in someClasses) {
    val myObject = myClass()
    myObject.doSomething()
}

Of course it doesn't work. Is it possible to do something like this in Kotlin?

Upvotes: 1

Views: 468

Answers (1)

Joffrey
Joffrey

Reputation: 37660

You could have a list of functions that create instances of said classes.

The simplest way to do it is to reference the constructor of those classes using the syntax ::ClassName. So, applying this to your example, assuming those classes have no-arg constructors:

val someClassConstructors = listOf(::ClassA, ::ClassB, ...)
for (myConstructor in someClassConstructors) {
    val myObject = myConstructor()
    myObject.doSomething()
}

The above assumes that all your classes implement a common interface that has the doSomething() method.

Upvotes: 5

Related Questions