🚀 Kotlin – Constructors (Primary & Secondary): Initialize Your Classes Effectively
🧲 Introduction – Why Learn Kotlin Constructors?
Constructors in Kotlin are used to initialize class properties and logic when an object is created. Kotlin simplifies constructor usage by offering:
- A clean primary constructor syntax
- Flexible secondary constructors for alternative initialization
- An optional
init
block to execute logic after object creation
🎯 In this guide, you’ll learn:
- What primary and secondary constructors are
- How to use default values and initializer blocks
- Best practices for constructor overloading
- Real examples to help you design classes clearly
🧱 What Is a Constructor in Kotlin?
A constructor is a special block that gets called when you create an object. It prepares the object for use by assigning values to its properties.
Kotlin supports two types:
- Primary constructor – defined in the class header
- Secondary constructor – defined using
constructor
keyword inside the class body
🔧 Primary Constructor – Simple and Clean
class Person(val name: String, var age: Int)
🔹 Usage:
val p = Person("Alice", 30)
println("${p.name}, ${p.age}")
✔️ val
/var
in the constructor automatically creates properties and assigns values.
🔁 Initializer Block – init
Used to add logic after the primary constructor is executed.
class User(val username: String) {
init {
println("User $username has been created.")
}
}
🟢 Output:
User John has been created.
✔️ Great for logging, validation, or conditional logic on creation.
🔄 Secondary Constructor – For Alternate Initialization
Used when you want multiple ways to construct an object.
class Book {
var title: String
var author: String
constructor(title: String, author: String) {
this.title = title
this.author = author
}
}
🔹 Usage:
val b = Book("1984", "George Orwell")
🔀 Combining Primary and Secondary Constructors
class Laptop(val brand: String) {
var price: Int = 0
constructor(brand: String, price: Int) : this(brand) {
this.price = price
}
}
✔️ Secondary constructors must call the primary constructor using : this(...)
.
🧠 Default Values in Constructors
Kotlin lets you assign default parameter values, reducing the need for overloading.
class Vehicle(val type: String = "Car", val speed: Int = 100)
val v1 = Vehicle()
val v2 = Vehicle("Bike", 80)
🟢 Output:
Vehicle(type=Car, speed=100)
Vehicle(type=Bike, speed=80)
🔐 Constructor Visibility Modifiers
You can control constructor access:
class Secret private constructor(val code: String) {
// Only accessible inside the class or companion object
}
✔️ Use private constructor
for singleton patterns or restricted object creation.
🚫 Common Mistakes
❌ Mistake | ✅ Fix |
---|---|
Not calling primary from secondary | Use : this(...) in secondary constructor |
Redundant secondary constructors | Prefer default values in primary constructor |
Duplicating logic across constructors | Use init block for shared logic |
Declaring constructor without val /var | Add val or var to create properties |
✅ Best Practices for Kotlin Constructors
Tip | Why It Helps |
---|---|
Use primary constructor with default values | Simplifies object creation |
Avoid multiple secondary constructors | Prevents confusion and reduces boilerplate |
Encapsulate logic in init | Cleanly separates logic from parameter definitions |
Use visibility modifiers wisely | Controls object creation scope |
📌 Summary – Recap & Next Steps
Kotlin constructors let you initialize objects quickly and clearly, with support for multiple approaches. Use the primary constructor for concise design, and secondary constructors only when necessary.
🔍 Key Takeaways:
- Primary constructor is preferred for simplicity and clarity
- Use
init
block for setup logic - Use default values instead of overloading
- Secondary constructors should call the primary constructor
⚙️ Practical Use:
Constructor patterns are essential in domain models, form data wrappers, Android component creation, and configuration-driven initialization.
❓ FAQs – Kotlin Constructors
❓ What is the difference between primary and secondary constructors in Kotlin?
✅ Primary is declared in the class header and is preferred. Secondary is defined inside the body and allows alternate initialization paths.
❓ Can a class have both primary and secondary constructors?
✅ Yes. But if secondary constructors are used, they must call the primary using : this(...)
.
❓ When should I use the init
block?
✅ Use it for logic that must run after primary constructor, like logging, validation, or computation.
❓ Can I assign default values in constructors?
✅ Yes! Kotlin supports default values:
class Car(val brand: String = "Tesla")
❓ How do I restrict constructor usage?
✅ Use a visibility modifier like private constructor
to limit instantiation scope.
Share Now :