June 2018
Intermediate to advanced
316 pages
6h 34m
English
An object inside a class can be marked with the companion keyword. Companion objects are created when a class is loaded into memory. Working with members of companion objects is similar to working with static members, but you have to remember that these members are still instances of another class.
Let's look at the following example:
class Main private constructor() { private var id: Int? = null companion object { var prevId = -1 fun newInstance(): Main { val main = Main() main.id = ++prevId return main } }}
This code contains the Main class with a private constructor, the id property, and a companion object. The companion object has the prevId property. This property holds a unique identifier of a previously created instance ...
Read now
Unlock full access