Junior — Middle
Millises järjekorras toimub omaduste initsialiseerimine ja koodiblokkide täitmine objekti loomisel, sealhulgas companion object, init plokk, konstruktoris olevad muutujad ja tavalised muutujad?
sobes.tech AI
Vastus AI-lt
When creating an object in Kotlin, the initialization order is as follows:
- Initialization of the companion object — occurs once when the class is loaded, before creating instances.
- Initialization of properties declared in the class body (including those declared outside the constructor) — they are initialized in the order of declaration.
- Execution of init blocks — they are executed in the order they are declared in the class, immediately after property initialization.
- Initialization of properties declared in the constructor (e.g., val/var parameters) — they are initialized when the constructor is called.
Example:
class Example(val constructorProp: String) {
val property1 = println("property1 initialized")
init {
println("init block 1")
}
val property2 = println("property2 initialized")
init {
println("init block 2")
}
companion object {
init {
println("companion object initialized")
}
}
}
fun main() {
val example = Example("constructor")
}
The output will be approximately:
companion object initialized
property1 initialized
init block 1
property2 initialized
init block 2
This way, the companion object is initialized once when the class is loaded, then, when creating an object, properties are initialized and init blocks are executed in declaration order, and constructor parameters are initialized when the constructor is called.