Constructors

Sometimes we may want to inspect the available constructors on a type. Perhaps we need to create a type that has a constructor that requires values. Or perhaps we want to determine which fields are needed to create an instance of a type at runtime. Or, similarly, perhaps we want to see if a class can be created from the parameters we have available.

We can return a list of all the constructors declared on a given type by using the constructors property available on the KClass type. This property returns a list of KFunction reflective instances, since constructors are themselves functions, just functions defined in a special way:

 fun <T : Any> printConstructors(kclass: KClass<T>) { kclass.constructors.forEach { println(it.parameters) ...

Get Programming Kotlin now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.