Kotlin and Android Full Course: https://www.udemy.com/course/kotlin-m...
What are Kotlin secondary constructors?
In Kotlin, secondary constructors are additional constructors within a class that allow you to provide different ways to initialize an object. They are defined using the `constructor` keyword and can complement the primary constructor. Secondary constructors must delegate to the primary constructor using the `this` keyword or to another secondary constructor of the same class.
Here's a basic example:
```kotlin
class Person {
var name: String = ""
var age: Int = 0
// Primary constructor
constructor(name: String) {
this.name = name
}
// Secondary constructor
constructor(name: String, age: Int) : this(name) {
this.age = age
}
}
```
In this example, the secondary constructor takes both name and age parameters, and it delegates to the primary constructor using `this(name)`. This ensures that the initialization logic in the primary constructor is executed before the secondary constructor's logic.