Analysis of associated objects of Kotlin and associated objects of kotlin
Companion object analogy Java
Do you still remember static members in Java? Attributes and Methods declared as static idioms are initialized during class loading and parsing, and their lifecycles are bound with the lifecycles of the class.
1. In this way, some variables and methods in the class can be bound to the class, rather than bound to an object to increase its lifecycle.
2. In this way, the object of this class can share this variable and method, without allocating resources for this variable to each object and saving resources.
How does Kotlin handle it?
Kotlin does not contain static variables, So. It uses companion objects to simulate static variables in Java. The companion object is also initialized during class loading. Similarly, the lifecycle is the same as that of the class and can be called directly by class name. (attribute, method. Multiple objects in this class share the associated object.
Why does one single object in Kotlin include all static resources?
In fact, the answer can be obtained from the class loading mechanism in Java. In the initialization phase of the class loading stage, the init () function will be called to initialize in sequence according to the static attributes and the static initial code block, the companion object here can be considered as an encapsulation of the init () function.
Languages are actually the same. We should be good at analogy and analysis in our learning process, so that no matter what language we face, you can get started quickly and easily.