Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Kotlin
Stage 5: Specialization

Part 07 / Topic 3 of 7

Secondary constructors: a second way to build the same class

A secondary constructor is written with the constructor keyword inside the class body. It cannot set up the object by itself -- it must delegate to the primary constructor (directly, or through another secondary constructor) using : this(...).

class BankAccount(val accountHolder: String, val accountNumber: String, openingBalance: Double) {
    var balance: Double = openingBalance

    init {
        require(openingBalance >= 0.0) { "openingBalance cannot be negative, was $openingBalance" }
    }

    // delegates straight to the primary constructor
    constructor(accountHolder: String, accountNumber: String) : this(accountHolder, accountNumber, 0.0) {
        println("Opened a zero-balance account for $accountHolder")
    }

    // delegates to the FIRST secondary constructor, which then delegates to the primary --
    // delegation can chain
    constructor(accountHolder: String) : this(accountHolder, "PENDING") {
        println("No account number yet for $accountHolder -- will be assigned at the branch")
    }

    fun summary() = "$accountHolder | $accountNumber | ₹$balance"
}
val asha = BankAccount("Asha Kulkarni", "AC1001", 5000.0)
println(asha.summary())

val ravi = BankAccount("Ravi Shah", "AC1002")
println(ravi.summary())

val meera = BankAccount("Meera Nair")
println(meera.summary())
Asha Kulkarni | AC1001 | ₹5000.0
Opened a zero-balance account for Ravi Shah
Ravi Shah | AC1002 | ₹0.0
Opened a zero-balance account for Meera Nair
No account number yet for Meera Nair -- will be assigned at the branch
Meera Nair | PENDING | ₹0.0

Watch the order of the printed lines for meera: the primary constructor's own validation runs first (silently, since it passes), then the first secondary constructor's body prints "Opened a zero-balance account...", then control returns to the second secondary constructor's body, which prints its own line last. Delegation runs inward to outward -- the primary constructor always finishes its work before any secondary constructor body runs.

Full program: examples/03_secondary_constructors.kt.

Done here? The practice set for Part 7 — including the solutions — is on the part page.

Search the guide