A secondary constructor in Kotlin is an auxiliary constructor defined within the class body using theDocumentation Index
Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
Use this file to discover all available pages before exploring further.
constructor keyword. It provides alternative ways to instantiate a class by accepting different parameter signatures and executing specific initialization logic.
Idiomatic Kotlin: Default Arguments
In Kotlin, secondary constructors are rarely required. Constructor overloading is idiomatically handled by defining default arguments directly in the primary constructor. This eliminates the boilerplate of writing multiple secondary constructors just to handle omitted parameters. Secondary constructors are typically only introduced when default arguments cannot express the required initialization logic, or when interoperating with Java frameworks that require specific constructor signatures.Syntax
Secondary constructors are declared inside the class block. Unlike primary constructors, they cannot declare class properties; parameters passed to a secondary constructor cannot be prefixed withval or var and act strictly as local variables within the constructor’s scope.
Delegation Rules
Kotlin enforces strict delegation rules for secondary constructors depending on the presence of a primary constructor. 1. With a Primary Constructor If a class declares a primary constructor, every secondary constructor must delegate to it, either directly or indirectly (via another secondary constructor). Delegation to another constructor in the same class is handled using thethis keyword.
super keyword, or delegate to another secondary constructor that eventually calls super. If the superclass has a default no-argument constructor, the super() call is implicit.
Execution Order
When a class is instantiated via a secondary constructor, the initialization sequence follows a strict hierarchy. In Kotlin, the primary constructor does not have a separate body; its execution consists of delegating to the superclass and then running the property initializers andinit blocks.
The execution order is:
- Primary Constructor Delegation: The secondary constructor delegates to the primary constructor (or directly to the superclass if no primary constructor exists). This delegation executes the superclass constructor, followed immediately by the class-level property initializers and
initblocks in the exact top-to-bottom order they are defined in the class body. - Secondary Constructor Body: Once the delegation phase completes, the body of the secondary constructor executes last.
Master Kotlin with Deep Grasping Methodology!Learn More





