Sobes.tech
Junior — Middle

Is it possible to define a class with multiple constructors in Kotlin?

sobes.tech AI

Answer from AI

Yes, in Kotlin, you can define a class with multiple constructors. This is done using one primary constructor and one or more secondary constructors.

The primary constructor is declared in the class header, while secondary constructors are declared inside the class body with 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 takes name and age. The secondary constructor calls the primary one via : this(name) and initializes the additional property.