Sobes.tech
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 init blocks.
  • Properties declared in the primary constructor with val or var become class properties.
  • Constructor parameters can be used in init blocks 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 constructor keyword 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 constructor keyword.
  • Can delegate to another constructor of the class using this() or to the superclass constructor using super(). 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:

  1. Execution of primary constructor code (if any).
  2. Execution of init blocks in the order they are declared.
  3. 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.

What are the features of working with constructors… - sobes.tech