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 the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.