Constructor initialization vs Init block in Kotlin

Hi, I am wondering Kotlin init block initialization is equivalent to Double bracket initialization in Java?

/**
 * Created by abubacker.siddik
 */
class TestDBI(val names : String) {
    var name : String by Delegates.notNull()
    var dbi : String by Delegates.notNull()

    init {
        this.name = names
        dbiInit("DBI Initialization")
    }

    fun dbiInit(value: String){
        dbi = value
    }
}

I can use the normal constructor as well in this case. Wondering why i would use init block in Kotlin?

Normal Constructor example:

/**
 * Created by abubacker.siddik
 */
class TestDBI {
    var name : String by Delegates.notNull()
    var dbi : String by Delegates.notNull()

    constructor(names : String) {
        this.name = names
        dbiInit("DBI Initialization")
    }

    fun dbiInit(value: String){
        dbi = value
    }
}
3 Likes

One thing, init is used for all constructors (in file order) so you can have multiple constructors (without a primary) that initialize core values and then don’t have to worry about whether or not you actually invoked your shared init code. In your example you probably would not have yet another dbiInit function, and the name field should probably be initialized at declaration.

5 Likes

Hope you are referring to this below.

/**
 * Created by abubacker.siddik
 */
class TestDBI(names: String) {
    var first : String by Delegates.notNull()
    var second : String by Delegates.notNull()
    var dbi : String by Delegates.notNull()

    init {
        this.first = names
        dbiInit("DBI Initialization")
    }

    constructor(first: String, second: String) : this(first){
        this.second = second
    }

    fun dbiInit(value: String){
        this.dbi = value
    }
}

fun main(args: Array<String>){
    val testDBI = TestDBI("First", "Second")
    println(testDBI.dbi)
    println(testDBI.first)
    println(testDBI.second)
}

I have not explicitly called init block here in the secondary constructor, yet dbi value is initialized. In this case, we call primary constructor (this()) in the secondary constructor that will always invoke init block. So can i conclude init block is primary constructor initializer?

While there is some overlap between the two Kotlin’s version is more powerful. You have access to the primary constructor parameters with Kotlin. With Kotlin’s you can place it after member properties are initialized based on those parameters as well.