Kotlin Constructors: Primary & Secondary Explained 🚀
Imagine you're filling out an online form to register for a course. You can:
1️⃣ Enter all details upfront and submit. ✅
2️⃣ Enter only basic details first and add more information later. 🔄
This is exactly how constructors work in Kotlin!
- Primary Constructor: 📜 Defines all properties in one place.
- Secondary Constructor: 🔄 Allows additional ways to create objects with different inputs.
📌 In this blog, we’ll explore:
✅ What is a Constructor? 🤔
✅ Primary Constructor 🏗️
✅ Secondary Constructor 🔄
✅ init
Block 🔥
✅ Constructor Overloading ⚙️
✅ Real-World Applications 🌍
1️⃣ What is a Constructor? 🤔
📌 A constructor is a special function that initializes an object when it is created.
💡 Think of it like a factory that builds objects!
Kotlin has two types of constructors:
Type | Description |
---|---|
Primary Constructor | Declared in the class header (short & clean). |
Secondary Constructor | Defined inside the class body (for flexibility). |
2️⃣ Primary Constructor 🏗️
📌 A Primary Constructor is the main way to initialize a class.
📌 It doesn’t have a body and is defined in the class header.
🔹 Example: A Simple Person
Class
class Person(val name: String, var age: Int) {
fun greet() {
println("Hello, my name is $name and I am $age years old.")
}
}
val p1 = Person("Alice", 25)
p1.greet()
// Output: Hello, my name is Alice and I am 25 years old.
✅ No need to define name
and age
separately – the primary constructor does it!
3️⃣ init
Block 🔥 (For Extra Initialization)
📌 The init
block is executed when the object is created.
📌 Used to run additional logic during initialization.
🔹 Example: Using init
to Print a Message
class Person(val name: String, var age: Int) {
init {
println("A new person named $name, aged $age, has been created!")
}
}
val p2 = Person("Bob", 30)
// Output: A new person named Bob, aged 30, has been created!
✅ Perfect for logging, validation, or additional setup!
4️⃣ Secondary Constructor 🔄
📌 A Secondary Constructor lets us create objects in multiple ways.
📌 It must call the primary constructor using this()
.
🔹 Example: Adding a Default Age
class Person(val name: String, var age: Int) {
// Secondary Constructor
constructor(name: String) : this(name, 18) {
println("$name is assigned a default age of 18.")
}
}
val p3 = Person("Charlie")
// Output: Charlie is assigned a default age of 18.
✅ This allows us to create a Person
with just a name, defaulting to age 18!
5️⃣ Constructor Overloading ⚙️
📌 Overloading means defining multiple constructors with different parameters.
🔹 Example: Multiple Ways to Create a Car
class Car(val brand: String, var speed: Int) {
// Secondary Constructor with only brand
constructor(brand: String) : this(brand, 0) {
println("$brand car created with default speed 0 km/h.")
}
fun accelerate() {
speed += 10
println("$brand is now moving at $speed km/h")
}
}
val car1 = Car("Tesla", 50)
val car2 = Car("BMW") // Uses the secondary constructor
car2.accelerate()
// Output: BMW car created with default speed 0 km/h.
// BMW is now moving at 10 km/h.
✅ We can now create a car with just a brand or with both brand and speed!
6️⃣ Real-World Applications 🌍
🔹 1. User Registration System
class User(val name: String, val email: String) {
// Secondary Constructor for users without email
constructor(name: String) : this(name, "Not Provided") {
println("Email not provided for $name.")
}
}
val u1 = User("Alice", "alice@example.com")
val u2 = User("Bob")
// Output: Email not provided for Bob.
✅ Helps in cases where some data may be optional!
🔹 2. Bank Account System
class BankAccount(val accountNumber: String, var balance: Double) {
// Secondary Constructor for new accounts with 0 balance
constructor(accountNumber: String) : this(accountNumber, 0.0) {
println("New account $accountNumber created with zero balance.")
}
}
val acc1 = BankAccount("12345", 1000.0)
val acc2 = BankAccount("67890")
// Output: New account 67890 created with zero balance.
✅ Allows flexibility in initializing different kinds of accounts!
🔟 Conclusion: Why Use Primary & Secondary Constructors? 🎯
✅ Primary Constructor: Short and clean initialization.
✅ init
Block: Extra setup after the object is created.
✅ Secondary Constructor: More flexibility in object creation.
✅ Constructor Overloading: Multiple ways to initialize a class.
💡 Next time you design a class, think about whether you need a primary, secondary, or both! 🚀
💬 What’s your favorite use case for Kotlin constructors? Let me know in the comments! ⬇️😊