Sobes.tech
Junior — Middle

Kas Kotlinis on võimalik määratleda klass mitme konstruktoriga?

sobes.tech AI

Vastus AI-lt

Yes, in Kotlin it is possible to define a class with multiple constructors. For this, one primary constructor and one or more secondary constructors are used.

The primary constructor is declared in the class header, and the secondary ones — inside the class body with the keyword constructor.

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 — name and age. The secondary constructor calls the primary via : this(name) and initializes the additional property.