Constructors in Kotlin - Primary and Secondary


Constructors are crucial for initializing objects in Kotlin classes. Kotlin supports both primary and secondary constructors, providing flexibility in how you create and initialize instances of your classes. In this guide, we'll delve into primary and secondary constructors in Kotlin.


Primary Constructor

The primary constructor is declared in the class header. It allows you to initialize properties and execute code when an object is created. Here's an example:

class Person(firstName: String, lastName: String) {
val fullName: String
init {
fullName = "$firstName $lastName"
}
}

In this example, the primary constructor takes two parameters, firstName and lastName. The init block is used to initialize the fullName property.


Secondary Constructor

Secondary constructors are additional constructors that provide alternative ways to create objects. They are defined in the class body using the constructor keyword. Here's an example:

class Rectangle(width: Int, height: Int) {
val area: Int
constructor(side: Int) : this(side, side) {
// Secondary constructor calls the primary constructor
area = width * height
}
}

In this example, the class has a primary constructor with width and height parameters and a secondary constructor that takes a single side parameter and calculates the area based on the side length.


Usage of Constructors

To create an object with a primary or secondary constructor, you simply call the class's constructor:

val person = Person("John", "Doe")
val square = Rectangle(5)

You can use the constructor that suits your object initialization needs.


Conclusion

Constructors in Kotlin play a crucial role in creating and initializing objects. Primary constructors are declared in the class header, while secondary constructors are defined in the class body. Understanding how to use primary and secondary constructors allows you to create flexible and user-friendly classes in Kotlin.


Happy coding!