Associated Objects
analogy Java
Do you still remember static statically members in Java? Attributes and methods declared as static idioms are initialized at class loading, parsing, and then their lifecycle is bound to the life cycle of the class.
1. This allows certain variables and methods in a class to be bound to the class, rather than bound to an object, to increase its life cycle.
2. This allows objects of this class to share this variable and method without allocating resources for each object, saving resources. How did Kotlin deal with that?
There is no static variable in Kotlin, so, it uses the associated object to mimic the role of static variables in Java. The associated object is also initialized in class loading, and the same life cycle is consistent with the life cycle of the class and can also be passed directly through the class name. (Attribute,method) to invoke. Multiple objects of the class share the associated object.
Why is there a single object in Kotlin to include all static resources?
In fact, the answer can be obtained from the class loading mechanism in Java, during the initialization phase of the class loading phase, the init () function is called to initialize in the order of static properties and static initial code blocks, where the associated object can be estimated as encapsulation of the init () function.
Language is actually the same, we learn to be good at analogy and analysis, so regardless of the face of any language, you can quickly get started, easy.