Analysis of associated objects of Kotlin and associated objects of kotlin

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.