Tell me about initializers in classes in Kotlin.
sobes.tech AI
Answer from AI
In Kotlin, classes can have a primary constructor and one or more secondary constructors. Initializers are init blocks that execute in the order they are declared after the primary constructor (if it exists) or after the secondary constructor if the primary does not.
Primary Constructor
Declared directly in the class header. It can contain parameters used for property initialization.
class User(name: String, age: Int) {
init {
// This block executes when an instance of the class is created
println("User created: $name, $age")
}
}
Secondary Constructors
Declared with the constructor keyword and must delegate to another constructor of the same class, either the primary (via this) or another secondary.
class User {
init {
// This block executes first if there is a primary constructor
}
constructor(name: String) : this() {
// Secondary constructor 1
println("User created with name: $name")
}
constructor(name: String, age: Int) : this(name) {
// Secondary constructor 2, calls the first secondary
println("User created with name and age: $name, $age")
}
}
Execution Order
- Code in the primary constructor (if parameters are present, they are used).
initblocks in sequence.- Code in the called secondary constructor (after delegation).
Example of execution order:
class Example {
init {
println("Init block 1")
}
constructor(i: Int) {
println("Secondary constructor $i")
}
init {
println("Init block 2")
}
}
fun main() {
Example(10)
}
Output:
Init block 1
Init block 2
Secondary constructor 10
Even if a secondary constructor is called, init blocks always execute before its body. This guarantees that the main object initialization is completed before executing specific secondary constructor code.
Initializers are essential for executing logic that must run when any instance of the class is created, regardless of which constructor is used. For example, input validation or setting up object state.