'When does init block of object get called?

I tried to know when the init block of object gets called in Kotlin using the below code, but I don't get any result in the console:

fun main(args: Array<String>) {
    TestObj
    TestObj
}

object TestObj {
    var count = 0

    init {
        fun howManyTimes() {
            println(++count)
        }
    }
}


Solution 1:[1]

You are not getting any output in console, because you are declaring function inside the init block, and not calling it.

Change TestObj code to:

object TestObj {

    var count = 0

    init {
        howManyTimes()
    }

    fun howManyTimes() {
        println(++count)
    }
}

Solution 2:[2]

Above answer gives a clear explanation as to why you are not getting expected output, I would try to answer your question

When does init block of object get called?

From kotlin in action

The init keyword introduces an initializer block. Such blocks contain initialization code that’s executed when the class is created, and are intended to be used together with primary constructors. Because the primary constructor has a constrained syntax, it can’t contain the initialization code; that’s why you have initializer blocks. If you want to, you can declare several initializer blocks in one class.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tamir Abutbul
Solution 2 mightyWOZ