Kotlin Constructors
Kotlin Constructors
In Kotlin, constructors are special blocks used to initialize objects.
Kotlin provides two types of constructors:
Primary Constructor
Secondary Constructor
Kotlin constructors are simpler and more powerful than Java.
1. Primary Constructor (Most Important)
The primary constructor is defined in the class header.
Basic Example
This only defines parameters, not properties.
Primary Constructor with Properties
Use val or var to create class properties.
Usage:
2. init Block
The init block runs immediately after the primary constructor.
➡ Multiple init blocks are allowed (executed top to bottom).
3. Primary Constructor with Default Values
Usage:
4. Secondary Constructor
Secondary constructors are defined using the constructor keyword.
5. Calling Primary Constructor from Secondary Constructor
If a class has a primary constructor, all secondary constructors must call it.
➡ this(name) calls the primary constructor.
6. Constructor with Visibility Modifiers
Usage:
Useful for:
Singleton patterns
Factory methods
7. Constructor with Annotations
Useful for Java interoperability.
8. Order of Initialization (Very Important)
Order:
Property initializers
initblocksSecondary constructor body
9. Constructor vs init Block
| Constructor | init Block |
|---|---|
| Takes parameters | Executes logic |
| One primary | Multiple allowed |
| Defines properties | Validation / setup |
10. Real-World Example
Summary
Primary constructor is preferred
Use
initfor initialization logicSecondary constructors are optional
Kotlin reduces constructor boilerplate
Clean & readable object initialization
