Companion objects

Companion objects are declared within a class by utilizing the companion and object keywords. You can use functions that are static within a companion object:

class Printer {  companion object DocumentPrinter {    fun printDocument() = println("Document printing successful.")  }}fun main(args: Array<String>) {  Printer.printDocument() // printDocument() invoked via companion object  Printer.Companion.printDocument() // also invokes printDocument() via                                     // a companion object}

Sometimes, you may want to give an identifier to a companion object. This can be done by placing the name after the object keyword. Consider the following example:

class Printer { companion object DocumentPrinter { // Companion object identified by DocumentPrinter ...

Get Kotlin Programming By Example 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.