Sobes.tech
Junior — Middle

How to implement multiple constructors in one class in Kotlin?

sobes.tech AI

Answer from AI

In Kotlin, to implement multiple constructors within a single class, one primary constructor and one or more secondary constructors are used. Secondary constructors are declared using the constructor keyword inside the class body and must call either the primary constructor or another secondary constructor.

Example:

class User(val name: String, val age: Int) {
    // Secondary constructor with one parameter
    constructor(name: String) : this(name, 0) {
        // additional logic
    }

    // Secondary constructor without parameters
    constructor() : this("Unknown", 0)
}

Here, the primary constructor takes name and age, while the secondary constructors provide alternative ways to create an object with different sets of parameters.