Sobes.tech
Junior — Middle

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

sobes.tech AI

Answer from AI

In Kotlin, you can define multiple constructors in a class using:

  • Primary constructor — declared in the class header.
  • Secondary constructors — declared inside the class body with the constructor keyword.

Example:

class User(val name: String) { // primary constructor
    var age: Int = 0

    constructor(name: String, age: Int) : this(name) { // secondary constructor
        this.age = age
    }
}

Thus, a class can have one primary and several secondary constructors, allowing the creation of objects with different sets of parameters.