tutorial, no_image, kotlin,

Kotlin - no_image

Upendra Upendra Follow Jan 23, 2025 · 1 min read
Kotlin - no_image
Share this

Constructors invocation order

Suppose we have next code:

open class Parent {

    private val a = println("Parent.a")

    constructor(arg: String = "Default arg for parent") {
        println("Parent primary constructor")
        println("Parent arg value = $arg")
    }

    init {
        println("Parent.init")
    }

    private val b = println("Parent.b")
}

class Child: Parent {

    private val a = println("Child.a")

    init {
        println("Child.init 1")
    }

    constructor(arg: String = "Default arg for child"): super(arg) {
        println("Child primary constructor")
    }

    constructor(arg: Int): this(arg.toString()) {
        println("Child secondary constructor")
    }

    init {
        println("Child.init 2")
    }
}

What will be displayed in the console in the following cases:

  • Parent()
  • Parent("Value")
  • Child()
  • Child("Value")
  • Child(IntValue)
Parent() ``` Parent.a Parent.init Parent.b Parent primary constructor Parent arg value = Default arg for parent ```
Parent(Value) ``` Parent.a Parent.init Parent.b Parent primary constructor Parent arg value = Value ```
Child() ``` Parent.a Parent.init Parent.b Parent primary constructor Parent arg value = Default arg for child Child.a Child.init 1 Child.init 2 Child primary constructor ```
Child(Value) ``` Parent.a Parent.init Parent.b Parent primary constructor Parent arg value = Value Child.a Child.init 1 Child.init 2 Child primary constructor ```
Child(IntValue) ``` Parent.a Parent.init Parent.b Parent primary constructor Parent arg value = 2 Child.a Child.init 1 Child.init 2 Child primary constructor Child secondary constructor ```

Tips: Code in initializer blocks effectively becomes part of the primary constructor. Delegation to the primary constructor happens as the first statement of a secondary constructor, so the code in all initializer blocks and property initializers is executed before the body of the secondary constructor.

Links

Classes

Further reading

Kotlin Constructors

An in-depth look at Kotlin’s initializers

credit goes to @swayangjit
Join Newsletter
Get the latest news right in your inbox. We never spam!
Upendra
Written by Upendra Follow
Hi, I am Upendra, the author in Human and machine languages,I don't know to how 3 liner bio works so just Connect with me on social sites you will get to know me better.