Class Human {private var work: String = "constructor" {constructor()} constructor(name: constructor) String) {println(" constructor $name")} init {println(" constructor $name")} init {println(" constructor $name")} init {println(" constructor $name") $work") } companion object { val instance: Human by lazy { Human("John") } init { println("companion init one") } init { println("companion init two") } } }Copy the code

Call Human() and you get the result:

Companion Init one Companion init two Human init Human init constructor

The constructor Human(“Tom”) with a parameter is called, and the result appears

Companion Init one Companion init two Human init Human init doctor

The constructor human.instance with a parameter is called, and the result appears

Companion Init one Companion init two Human init Human init doctor with argument subconstructor John

The Init block in Kotlin is the equivalent of the normal block in Java, which is executed first when the object is created. Note that each creation is performed

If the instance in the companion object is not lazily loaded, the result will appear

Human init

The Human init doctor

Constructor John

companion init one

companion init two

For companion objects, we can understand this simple

The companion object in Kotlin corresponds to the Static keyword in Java.

An init block in a companion object is the equivalent of a static block in Java. It is executed first and only once when the class is loaded.

Conclusion: Since the code in the companion object is executed when the class is loaded, the companion class initialization is executed first and then the constructor, merging the init code into the constructor, but inserting it first.

Refer to the article: blog.csdn.net/wuqiqi1992/…