What if you could create objects in many ways without messy code or confusion?
Why Secondary constructors in Kotlin? - Purpose & Use Cases
Imagine you are creating a class to represent a person. You want to create objects with different sets of information: sometimes just a name, other times a name and age, or even name, age, and address. Writing separate classes or many functions for each case quickly becomes confusing and messy.
Manually handling all these different ways to create a person means repeating code and risking mistakes. You might forget to initialize some properties or write duplicate logic. It becomes slow to write and hard to maintain, especially as your class grows.
Secondary constructors let you define multiple ways to create an object inside the same class. Each constructor can handle different input combinations, sharing common setup code. This keeps your code clean, organized, and easy to extend.
class Person(val name: String) {
var age: Int? = null
var address: String? = null
fun initWithAge(age: Int) {
this.age = age
}
fun initWithAddress(address: String) {
this.address = address
}
}class Person {
var name: String
var age: Int? = null
var address: String? = null
constructor(name: String) {
this.name = name
}
constructor(name: String, age: Int) : this(name) {
this.age = age
}
constructor(name: String, age: Int, address: String) : this(name, age) {
this.address = address
}
}Secondary constructors enable creating flexible and readable classes that handle multiple initialization scenarios effortlessly.
Think of a contact app where you can add a person with just a name, or with name and phone number, or with name, phone number, and email. Secondary constructors let you handle all these cases cleanly in one class.
Secondary constructors provide multiple ways to create an object in one class.
They reduce code duplication and improve clarity.
They make your classes flexible for different input data.