what is the use of secondary constructor in kotlin ?

Use of Secondary Constructor in Kotlin

In Kotlin, a secondary constructor is a constructor that allows you to provide additional ways to initialize an object of a class. It provides flexibility in object initialization by allowing different combinations of parameters to be used when creating an instance of a class.

Here are the steps to use a secondary constructor in Kotlin:

  1. Define the primary constructor: The primary constructor is defined in the class header and is responsible for initializing the primary properties of the class. It can also have default parameter values.

  2. Define the secondary constructor: To define a secondary constructor, use the constructor keyword followed by the parameter list. The secondary constructor must call the primary constructor using the this keyword or another secondary constructor using the this keyword with different parameters.

  3. Initialize additional properties: Inside the secondary constructor, you can initialize additional properties of the class or perform any other necessary initialization logic.

  4. Example: Here's an example that demonstrates the use of a secondary constructor in Kotlin:

class Person(val name: String, val age: Int) {
    var address: String = ""

    constructor(name: String, age: Int, address: String) : this(name, age) {
        this.address = address
    }
}

fun main() {
    val person1 = Person("John", 25)
    val person2 = Person("Jane", 30, "123 Main St")

    println(person1.name)    // Output: John
    println(person1.age)     // Output: 25
    println(person1.address) // Output: ""

    println(person2.name)    // Output: Jane
    println(person2.age)     // Output: 30
    println(person2.address) // Output: 123 Main St
}

In the example above, the Person class has a primary constructor that initializes the name and age properties. It also has a secondary constructor that takes an additional address parameter. The secondary constructor calls the primary constructor using the this keyword and then initializes the address property.

By providing a secondary constructor, you can create instances of the Person class using different combinations of parameters, allowing for more flexibility in object initialization.