Junior — Middle
How can you implement the creation of additional constructors for a class in Kotlin?
sobes.tech AI
Answer from AI
In Kotlin, secondary constructors are used to create additional constructors in a class. The primary constructor is declared in the class header, while secondary constructors are inside the class body using the constructor keyword.
Example:
class User(val name: String) {
var age: Int = 0
// Secondary constructor
constructor(name: String, age: Int) : this(name) {
this.age = age
}
}
Here, the primary constructor takes name, and the secondary constructor takes name and age. The secondary constructor must call the primary one using this(...). This allows creating objects with different sets of parameters.