What is Secondary Constructor in Kotlin: Simple Explanation
secondary constructor is an additional constructor inside a class that allows creating objects with different sets of parameters. It complements the primary constructor and provides more ways to initialize a class.How It Works
Think of a class like a recipe for making a cake. The primary constructor is the main recipe you usually follow. But sometimes, you want to make a cake with a slightly different method or ingredients. That's where a secondary constructor comes in—it offers an alternative way to create the cake.
In Kotlin, the primary constructor is declared in the class header, while secondary constructors are declared inside the class body using the constructor keyword. Each secondary constructor must either call the primary constructor directly or call another secondary constructor that eventually calls the primary one. This ensures the class is always properly initialized.
Example
This example shows a class with a primary constructor and a secondary constructor that provides an alternative way to create an object.
class Person(val name: String) { var age: Int = 0 // Secondary constructor constructor(name: String, age: Int) : this(name) { this.age = age } } fun main() { val person1 = Person("Alice") val person2 = Person("Bob", 30) println("Person1: name=${person1.name}, age=${person1.age}") println("Person2: name=${person2.name}, age=${person2.age}") }
When to Use
Use secondary constructors when you want to create objects in different ways but still keep a single primary constructor. For example, if you have a class where sometimes you only know the name, and other times you know both name and age, a secondary constructor lets you handle both cases cleanly.
They are helpful when you need multiple initialization options but want to keep your class organized and avoid repeating code. However, if you have many ways to create an object, consider using factory methods or default parameters for simpler code.
Key Points
- A secondary constructor is an extra constructor inside a Kotlin class.
- It uses the
constructorkeyword and must call the primary constructor directly or indirectly. - It allows creating objects with different sets of parameters.
- Use it to provide alternative ways to initialize a class.