kotlinconstructorinitialization-block

What is the difference between init block and constructor in kotlin?


I have started learning Kotlin. I would like to know the difference between init block and constructor. What is the difference between this and how we can use this to improve?

class Person constructor(var name: String, var age: Int) {
    var profession: String = "test"

    init {
        println("Test")
     }    
}

Solution

  • The init block will execute immediately after the primary constructor. Initializer blocks effectively become part of the primary constructor.

    The constructor is the secondary constructor. Delegation to the primary constructor happens as the first statement of a secondary constructor, so the code in all initializer blocks is executed before the secondary constructor body.

    Example

    class Sample(private var s : String) {
        init {
            s += "B"
        }
        constructor(t: String, u: String) : this(t) {
            this.s += u
        }
    }
    

    Think you initialized the Sample class with

    Sample("T","U")
    

    You will get a string response at variable s as "TBU".

    Value "T" is assigned to s from the primary constructor of Sample class.
    Then immediately the init block starts to execute; it will add "B" to the s variable.
    Next it is the secondary constructor turn; now "U" is added to the s variable to become "TBU".