October 2019
Intermediate to advanced
434 pages
11h 54m
English
An object declaration within another class can be marked with the companion keyword to become a companion object. Companion objects connect the initialization of an object declaration to the instantiation of the enclosing class, and there can be only a single companion object for a class. This lets us scope whatever functionality the object declaration provides to the namespace of the enclosing class, cleaning up the global namespace and adding useful semantics in many cases.
In this snippet, we've defined a companion object for SomeClass:
class SomeClass { companion object { fun foo() {} }}
We can access the companion object in one of the following two ways:
fun main(args: Array<String>) { SomeClass.Companion.foo() SomeClass ...
Read now
Unlock full access