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

Objects and companions


We can even get a reference to objects or companion objects through reflection. For example, take the following definition of a class and a companion object:

    class Aircraft(name: String, manufacturer: String, capacity: Int)  { 
      companion object { 
        fun boeing(name: String, capacity: Int) = Aircraft(name,  "Boeing", capacity) 
      } 
    } 

Given this, we can retrieve a reference to the companion object using the appropriately named companionObject property defined on the KClass type:

    val kclass = Aircraft::class 
    val companionKClass = kclass.companionObject 

From then on, we have another KClass instance, this one modeling the functions and members of the companion object.

In fact, using the companionObjectInstance property, we can even get a handle to the instance of the companion object. Then, we could invoke functions or access properties on it directly if we cast to the appropriate type:

    val kclass =...