Companion object

Companion is a keyword used in Kotlin. An object declaration inside a class can be marked as a companion object. All members of the companion object can be called using the class name directly. Sounds like static!

    class MyClass {      companion object Factory {        fun create(): MyClass = MyClass()      }    }

Calling can look as follows: 

    val instance = MyClass.create()
The name of a companion object can be omitted. There can be multiple companion objects inside a single class and they should have a name in this case.

Get Kotlin Blueprints 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.