In Kotlin, a class can have one primary constructor and one or more secondary constructors. The primary constructor is defined as part of the class header and is responsible for initializing the class.
On the other hand, secondary constructors are defined inside the class body and provide an additional way to initialize class properties. Secondary constructors are optional, and if they are present, they must directly or indirectly delegate to the primary constructor.
A class with a primary constructor:
class Person(firstName: String, age: Int) {
// Class properties
val firstName: String
val age: Int
init {
// Initialize class properties in the primary constructor
this.firstName = firstName
this.age = age
}
}
A class with both primary and secondary constructors:
class Person {
// Class properties
val firstName: String
val age: Int
constructor(firstName: String) {
// Initialize a few properties in the secondary constructor
this.firstName = firstName
this.age = 0
}
constructor(firstName: String, age: Int) {
// Initialize all the properties in the secondary constructor
this.firstName = firstName
this.age = age
}
}
To call a secondary constructor from a primary constructor in Kotlin, we can use the ‘this‘ keyword along with the required arguments. Here is an example:
class Person(firstName: String) {
val lastName: String
constructor(firstName: String, lastName: String) : this(firstName) {
// call to primary constructor to initialize firstName
this.lastName = lastName
}
}
In the above example, we have defined a secondary constructor that takes two arguments, ‘firstName‘ and ‘lastName‘. This constructor calls the primary constructor using the ‘this‘ keyword, passing only the ‘firstName‘ argument. After that, we can initialize ‘lastName‘ in the body of the secondary constructor. By doing this, we avoid duplicating the initialization logic of ‘firstName‘, which has already been done in the primary constructor.