Skip to main content
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, the 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 of val 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 init blocks.

Initialization Blocks

The primary constructor cannot contain executable code. Any setup logic or validation must be placed within one or more init 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).
Tired of Poor Kotlin Skills? Fix That With Deep Grasping!Learn More