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

Time:09-22

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?

CodePudding user response:

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.

  • Related