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
lazykeyword. The object is created upon the first access to it. -
When declaring properties with the
lateinitmodifier — the object is initialized later, but before the first use. -
When creating an object through a class constructor — initialization happens immediately upon calling
newor 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