Secondary constructors let you create extra ways to make objects with different starting information.
0
0
Secondary constructors in Kotlin
Introduction
When you want to create an object but have different sets of information available.
When you need to provide default values for some properties but allow others to be set.
When you want to offer simple ways to create an object without repeating code.
When the main constructor is not enough to cover all ways to create an object.
Syntax
Kotlin
class ClassName { constructor(param1: Type1) { // initialization code } constructor(param1: Type1, param2: Type2) { // initialization code } }
Secondary constructors are inside the class body.
Each secondary constructor starts with the constructor keyword.
Examples
This class has two ways to create a Person: with just a name or with a name and age.
Kotlin
class Person { var name: String var age: Int constructor(name: String) { this.name = name this.age = 0 } constructor(name: String, age: Int) { this.name = name this.age = age } }
Box can be created as a square or a rectangle using different constructors.
Kotlin
class Box { var width: Int var height: Int constructor(size: Int) { this.width = size this.height = size } constructor(width: Int, height: Int) { this.width = width this.height = height } }
Sample Program
This program shows two ways to create a Car object using secondary constructors. One sets a default year, the other sets a specific year.
Kotlin
class Car { var brand: String var year: Int constructor(brand: String) { this.brand = brand this.year = 2020 } constructor(brand: String, year: Int) { this.brand = brand this.year = year } } fun main() { val car1 = Car("Toyota") val car2 = Car("Honda", 2018) println("Car1: ${car1.brand}, Year: ${car1.year}") println("Car2: ${car2.brand}, Year: ${car2.year}") }
OutputSuccess
Important Notes
Secondary constructors can call the primary constructor using this() to avoid repeating code.
If a class has a primary constructor, secondary constructors must delegate to it either directly or indirectly.
Summary
Secondary constructors provide multiple ways to create objects with different inputs.
They help keep code clean by avoiding repeated initialization.
Use them when one constructor is not enough for your class needs.