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)
}
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With