Problem Statement
Explain primary and secondary constructors, init blocks, and the order of initialization in Kotlin.
Explanation
Primary constructors are declared in the class header and can have parameters marked as properties with val or var, while secondary constructors are defined in the class body with constructor keyword and must delegate to the primary constructor using this. Init blocks run during object construction in the order they appear in the class, after the primary constructor parameters are initialized, allowing you to add validation or initialization logic that can't be expressed in property initializers.
The initialization order is primary constructor parameters, property initializers and init blocks in the order they appear, then secondary constructor body. Properties declared with val or var in the primary constructor are available throughout the class including in init blocks and property initializers, but you cannot access properties before they're initialized leading to compile errors if order is wrong.
Use primary constructors for simple initialization with property declarations, init blocks for validation or initialization logic that needs multiple statements, and secondary constructors for providing alternative construction paths like default parameters or convenience constructors. Most classes only need a primary constructor possibly with default parameters, making secondary constructors less common in Kotlin than constructor overloading in Java.
