Middle
What are the features of working with constructors and object initialization in Kotlin?
sobes.tech AI
Answer from AI
In Kotlin, classes can have a primary constructor and one or more secondary constructors.
Primary constructor:
- Declared in the class header:
class User(val name: String, var age: Int = 0) { // class body } - Has no body. Initialization code is executed in
initblocks. - Properties declared in the primary constructor with
valorvarbecome class properties. - Constructor parameters can be used in
initblocks and property initializations:init { println("Initializing user $name") } val description = "User: $name, age: $age" - If the primary constructor has no annotations or visibility modifiers, the
constructorkeyword can be omitted.
init blocks:
- Contain initialization code executed when an instance of the class is created.
- Executed in the order they are declared in the class.
- Run after the primary constructor (if any) but before secondary constructors.
Secondary constructors:
- Declared with the
constructorkeyword. - Can delegate to another constructor of the class using
this()or to the superclass constructor usingsuper(). Delegation calls must be the first statement.class User(val name: String) { constructor(name: String, age: Int) : this(name) { println("Secondary constructor") // Additional initialization logic } } - If the class has a primary constructor, all secondary constructors must explicitly or indirectly delegate to it via
this().
Initialization order:
- Execution of primary constructor code (if any).
- Execution of
initblocks in the order they are declared. - Execution of secondary constructor code (if used).
Example:
class Example(name: String) {
init {
println("First init block for $name")
}
val property1 = "Property 1"
init {
println("Second init block for $name")
}
constructor(name: String, age: Int) : this(name) {
println("Secondary constructor for $name, age $age")
}
}
fun main() {
val ex1 = Example("User1") // Outputs: First init block for User1, Second init block for User1
val ex2 = Example("User2", 30) // Outputs: First init block for User2, Second init block for User2, Secondary constructor for User2, age 30
}
Key features: declarative syntax of the primary constructor, use of init blocks for initialization logic, explicit delegation in secondary constructors to ensure consistent object creation.