An initializer block is a designated code block prefixed with 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.
init keyword that executes during the instantiation of a Kotlin class. Because Kotlin’s primary constructor syntax does not allow for an execution body, initializer blocks serve as the execution environment for primary constructor logic.
Syntax
Execution Order and Interleaving
Initializer blocks are executed as part of the primary constructor’s lifecycle. If a class contains multipleinit blocks and class-level property initializers, they are evaluated sequentially in the exact top-to-bottom order they are declared within the class body.
Scope and Access Rules
- Primary Constructor Parameters: Parameters defined in the primary constructor are directly accessible within any
initblock in the class. - Property Visibility and Initialization: An
initblock can access and assign values to properties declared lexically above it. Attempting to read a property declared below theinitblock results in a compiler error. This error occurs strictly because the property is uninitialized at that point in the execution sequence. Memory for the entire object (including all properties) is allocated on the heap before any initialization logic runs, so the restriction is a safeguard against forward-referencing uninitialized state, not unallocated memory.
Relationship with Secondary Constructors
Initializer blocks are guaranteed to execute before the body of any secondary constructor. The exact mechanism depends on whether the class defines a primary constructor:- With a Primary Constructor: If a class has a primary constructor, any secondary constructor must explicitly delegate to it (either directly or indirectly) using
this(). Theinitblocks execute as part of that primary constructor invocation, before the secondary constructor’s body begins.
- Without a Primary Constructor: If a class lacks a primary constructor, secondary constructors must delegate to a superclass constructor (implicitly if the superclass has a no-argument constructor, or explicitly via
super(...)), or they can delegate to another secondary constructor within the same class usingthis(...). Theinitblocks execute immediately after the superclass constructor finishes, but prior to the execution of the secondary constructor’s body.
Master Kotlin with Deep Grasping Methodology!Learn More





