A primary constructor in Kotlin is the main entry point for class instantiation, defined directly within the class header. It immediately follows the class name and optional type parameters, serving to declare constructor parameters and, optionally, class-level properties in a single declaration. By default, 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 can be omitted unless the constructor requires visibility modifiers or annotations.
Parameter vs. Property Declaration
The primary constructor differentiates between standard parameters and class properties based on the presence ofval or var keywords.
val: Declares a read-only property. A backing field is generated, along with a getter.var: Declares a mutable property. A backing field is generated, along with a getter and a setter.- No keyword: Declares a standard constructor parameter. It does not become a class property and is only accessible within property initializers and
initblocks.
Initialization Blocks
The primary constructor cannot contain executable code. Any setup logic or validation must be placed within one or moreinit blocks.
During instantiation, init blocks and property initializers are executed in the exact order they appear in the class body. Primary constructor parameters are fully accessible within these blocks.
Modifiers and Annotations
If the primary constructor requires an annotation (e.g.,@Inject) or a visibility modifier (e.g., private, internal), the constructor keyword becomes mandatory. The modifiers are placed immediately before the constructor keyword.
Default Arguments
Primary constructor parameters can define default values. If all parameters have default values, the Kotlin compiler automatically generates an additional parameterless (no-arg) constructor, which is required by certain reflection-based frameworks (like Jackson or JPA).Master Kotlin with Deep Grasping Methodology!Learn More





