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

Part 07 / Topic 5 of 7

Custom getters and setters

Every property already has a getter (and a setter, if it's a var) even when you don't write one -- Kotlin generates the plain "store it, read it back" version. Writing your own lets a property validate on write, or compute its value fresh on every read.

class BankAccount(val accountHolder: String, openingBalance: Double) {
    // `private set` keeps this readable from outside (`account.balance` compiles fine), but
    // only code INSIDE this class can assign to it -- outside code must go through
    // deposit()/withdraw() instead of setting it directly
    var balance: Double = openingBalance
        private set

    // a custom setter with validation -- `field` is the real, hidden storage behind the
    // property; without writing to `field`, the new value is never actually kept
    var pin: String = "0000"
        set(value) {
            require(value.length == 4 && value.all { it.isDigit() }) {
                "PIN must be exactly 4 digits, got \"$value\""
            }
            field = value
        }

    // a custom getter -- runs fresh every time `.balanceDisplay` is read, never cached
    val balanceDisplay: String
        get() = "₹%.2f".format(balance)

    fun deposit(amount: Double) {
        require(amount > 0.0) { "deposit amount must be positive" }
        balance += amount
    }
}
val account = BankAccount("Asha Kulkarni", 1000.0)
println("Balance: ${account.balanceDisplay}")

account.deposit(500.0)
println("After deposit: ${account.balanceDisplay}")

account.pin = "4821"
println("PIN updated to ${account.pin}")

try {
    account.pin = "12"
} catch (e: IllegalArgumentException) {
    println("Rejected PIN: ${e.message}")
}
println("PIN is still ${account.pin}")
Balance: ₹1000.00
After deposit: ₹1500.00
PIN updated to 4821
Rejected PIN: PIN must be exactly 4 digits, got "12"
PIN is still 4821

account.balance = 999999.0 from main() does not compile at all -- the setter exists, but it's private, so only code inside BankAccount itself can call it. That's a stronger guarantee than "please don't set this directly" in a comment: the compiler enforces it.

🔍 Going deeper: field only exists inside a custom getter/setter, and only if the property needs real storage. val balanceDisplay above has no field of its own -- it's computed purely from balance every time, so there is nothing to back it with.

Full program: examples/05_custom_getters_setters.kt.

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

Search the guide