
Constructors in Kotlin
📌 Constructors in Kotlin
In Kotlin, a constructor is a special function used to initialize objects. It is called when an object of a class is created.
Kotlin supports two types of constructors:
Primary Constructor
Secondary Constructor
✅ 1. Primary Constructor
The primary constructor is part of the class header.
It is used to initialize class properties directly.
The keyword
constructor
is optional if there are no annotations or visibility modifiers.
📌 Syntax:
class ClassName(val property1: Type, var property2: Type) { // Class body}
📌 Example: Primary Constructor
class Person(val name: String, var age: Int) { fun () { println("Name: $name, Age: fun () { val person = Person("John", 25) person.displayInfo()}
Output:
Name: John, Age: 25
val name
→ Immutable property.var age
→ Mutable property.
📌 Primary Constructor with Initialization Block (init
)
The
init
block is executed when the object is created.It is useful for additional initialization or validation.
class Employee(val name: String, var salary: Double) { init { println("Employee $name created with salary fun main() { val emp = Employee("Alice", 5000.0)}
Output:
Employee Alice created with salary 5000.0
✅ 2. Secondary Constructor
Secondary constructors are defined using the
constructor
keyword inside the class body.They can include additional logic or initialization.
If the class has a primary constructor, the secondary constructor must call it using
this()
.
📌 Example: Secondary Constructor
fun () { println("Name: $name, Grade: fun () { val student1 = Student("Mark", "A") student1.displayInfo() val student2 = Student("Sophia") student2.displayInfo()}
Output:
Name: Mark, Grade: AGrade not provided, setting default grade.Name: Sophia, Grade: Not Assigned
✅ 3. Constructor with Default Values
Kotlin allows you to define default values for constructor parameters to make object creation more flexible.
📌 Example: Constructor with Default Values
class Car(val brand: String = "Toyota", val model: String = "Corolla", val year: Int = 2024) { fun () { println("Brand: $brand, Model: fun main() { val car1 = Car() car1.displayInfo() val car2 = Car("Honda", "Civic", 2023) car2.displayInfo()}
Output:
Brand: Toyota, Model: Corolla, Year: 2024Brand: Honda, Model: Civic, Year: 2023
✅ Conclusion
Use Primary Constructor for simple object initialization.
Use Secondary Constructor when additional initialization logic is needed.
Use init Block for executing code during object creation.
Provide Default Values for constructor parameters to simplify object creation.