How do you create secondary constructors in Kotlin?

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.

Nel

Nel

Author

Head of Content at Cloud Devs

As the Head of Content at Cloud Devs, I lead the strategy behind our brand voice, content creation, and distribution. From SEO to storytelling, I focus on producing content that drives engagement, builds trust, and converts the right audience. Every piece is built to educate, inspire, or sell—sometimes all three.

Related Articles

.. .. ..

Ready to make the switch to CloudDevs?

Hire today
7 day risk-free trial

Want to learn more?

Book a call