Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When does init block of object get called?

Tags:

kotlin

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)
        }
    }
}
like image 481
Hasan Al-Qaisi Avatar asked Dec 29 '25 08:12

Hasan Al-Qaisi


1 Answers

Dimitri's answer is correct for your problem, however the correct answer for your specific question is:

if it is a class instantiation, the init is executed before the constructor is called.

if it is an object, according to Kotlin documentation, it will be called whenever the (singleton) object is called first time, as static objects are lazy initialized.

like image 53
htafoya Avatar answered Jan 01 '26 18:01

htafoya



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!