Sobes.tech
Junior

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

sobes.tech AI

Answer from AI

In Kotlin, a class can have one primary constructor and one or more secondary constructors.

  1. Primary constructor: Defined in the class header. It can have parameters.

    class MyClass(private val someProperty: String) { // Primary constructor with a parameter
        // Class body
    }
    
  2. Secondary constructors: Declared with the keyword constructor. If the class has a primary constructor, each secondary constructor must delegate to it directly or indirectly using the this() keyword.

    class AnotherClass(private val primaryValue: Int) { // Primary constructor
    
        constructor(anotherValue: String) : this(anotherValue.length) { // Secondary constructor delegating to primary
            // Secondary constructor logic
            println("Created with string: $anotherValue")
        }
    
        constructor(value1: Int, value2: Int) : this(value1 + value2) { // Another secondary constructor
            // Logic
            println("Created with two ints: $value1, $value2")
        }
    }
    

If there is no primary constructor, secondary constructors are not required to delegate to other constructors of the same class (but they can).

class ClassWithoutPrimary {

    constructor(value: Int) {
        println("Created with int: $value")
    }

    constructor(value: String) {
        println("Created with string: $value")
    }
}