August 2017
Intermediate to advanced
440 pages
10h
English
A companion object is a singleton created by a companion class and kept in its static property. The instantiation of a companion object is lazy. This means that companion object will be instantiated when it is needed for the first time--when its members are accessed, or an instance of a class containing the companion object is created. To mark when the Car class instance and its corresponding companion object are created, we need to add two initializer blocks--one for the Car class, another for the companion object.
The initializer block inside the companion object works exactly the same way as in the class--it's executed when an instance is created:
class Car { init { count++; println("Car created") } companion ...Read now
Unlock full access