Kotlin Q & A

 

How do you create secondary constructors in Kotlin?

In Kotlin, secondary constructors complement the primary constructor by providing additional ways to initialize objects. While the primary constructor is declared within the class header, secondary constructors are defined within the class body and offer flexibility in object instantiation.

To create a secondary constructor in Kotlin, you use the constructor keyword followed by the constructor parameters and optional initialization logic. Unlike the primary constructor, secondary constructors do not declare properties; instead, they delegate initialization to the primary constructor or other secondary constructors using the this keyword.

Consider the following example:

kotlin

class Person {
 var name: String = ""
 var age: Int = 0

 constructor(name: String) {
 this.name = name
 }

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

In this example, the Person class defines two secondary constructors. The first constructor initializes the name property, while the second constructor initializes both the name and age properties, delegating the initialization of the name property to the primary constructor using this(name).

Secondary constructors enable flexible object initialization scenarios and provide alternative ways to construct objects based on varying requirements. They complement the primary constructor by allowing for additional initialization logic and parameter combinations, enhancing the versatility and usability of Kotlin classes.

Previously at
Flag Argentina
Brazil
time icon
GMT-3
Experienced Android Engineer specializing in Kotlin with over 5 years of hands-on expertise. Proven record of delivering impactful solutions and driving app innovation.