Sobes.tech
Junior

How can you implement multiple constructors in a single class in Kotlin?

sobes.tech AI

Answer from AI

To create multiple constructors in Kotlin, a primary constructor and, if necessary, one or more secondary constructors are used.

The primary constructor is declared directly in the class header:

class MyClass(primaryParam1: String, primaryParam2: Int) {
    // Class body
}

Secondary constructors are declared using the constructor keyword:

class MyClass {
    // Primary constructor (implicitly or explicitly)

    constructor(param1: String) {
        // Logic of secondary constructor 1
    }

    constructor(param1: String, param2: Int) {
        // Logic of secondary constructor 2
    }
}

If the class has a primary constructor, each secondary constructor must delegate to the primary constructor using the this() keyword:

class MyClass(primaryParam: String) {

    constructor(secondaryParam: Int) : this(secondaryParam.toString()) {
        // Logic of secondary constructor
    }
}

It is also possible to have multiple secondary constructors delegating to the primary constructor or to other secondary constructors (following the delegation hierarchy):

class MyClass(primaryParam: String) {

    constructor(param1: String, param2: Int) : this(param1) {
        // Logic of secondary constructor 1
    }

    constructor(param1: String, param2: Int, param3: Boolean) : this(param1, param2) {
        // Logic of secondary constructor 2
    }
}

Important points:

  • The body of the primary constructor executes before the bodies of secondary constructors.
  • Properties declared in the primary constructor header are accessible within the bodies of secondary constructors.
  • In Kotlin, it is recommended to use the primary constructor and, if possible, avoid using secondary constructors, preferring named arguments or factory methods.