Book Image

Programming Kotlin

Book Image

Programming Kotlin

Overview of this book

Quickly learn the fundamentals of the Kotlin language and see it in action on the web. Easy to follow and covering the full set of programming features, this book will get you fluent in Kotlin for Android.
Table of Contents (20 chapters)
Programming Kotlin
Credits
About the Authors
About the Reviewers
www.PacktPub.com
Customer Feedback
Preface

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) 
      } 
    } 

The preceding example simply iterates over each constructor, printing out the parameters it accepts. For example, look at the following defined class:

    class Kingdom(name:...