Sobes.tech
Junior — Middle

When does automatic object initialization occur in Kotlin?

sobes.tech AI

Answer from AI

In Kotlin, automatic object initialization occurs in several cases:

  • When using lazy initialization with the lazy keyword. The object is created upon the first access to it.

  • When declaring properties with the lateinit modifier — the object is initialized later, but before the first use.

  • When creating an object through a class constructor — initialization happens immediately upon calling new or creating an instance.

Example of lazy initialization:

val myObject: MyClass by lazy {
    println("Initialization")
    MyClass()
}

// "Initialization" will be printed only upon the first access to myObject