Part 07 / Topic 2 of 7
init blocks: validating at construction time
An init block runs once, right when the object is being built, in the exact position it
appears relative to property initializers in the class body. It's the standard place to reject
bad input before the object is ever handed back to the caller.
class BankAccount(val accountHolder: String, openingBalance: Double) {
var balance: Double = openingBalance
init {
require(accountHolder.isNotBlank()) { "accountHolder cannot be blank" }
require(openingBalance >= 0.0) { "openingBalance cannot be negative, was $openingBalance" }
println("Account created for $accountHolder with opening balance ₹$openingBalance")
}
// a class can have more than one init block -- each runs in the order it's written
init {
if (openingBalance >= 10000.0) {
println("$accountHolder qualifies for a premium account from day one")
}
}
}
val asha = BankAccount("Asha Kulkarni", 5000.0)
println("asha.balance = ${asha.balance}")
val ravi = BankAccount("Ravi Shah", 15000.0)
println("ravi.balance = ${ravi.balance}")
try {
BankAccount("", 1000.0)
} catch (e: IllegalArgumentException) {
println("Rejected blank name: ${e.message}")
}
Account created for Asha Kulkarni with opening balance ₹5000.0
asha.balance = 5000.0
Account created for Ravi Shah with opening balance ₹15000.0
Ravi Shah qualifies for a premium account from day one
ravi.balance = 15000.0
Rejected blank name: accountHolder cannot be blank
Rejected negative opening balance: openingBalance cannot be negative, was -500.0
Notice openingBalance itself is a plain constructor parameter, no val/var -- it's only
usable while the object is being built (inside init and in property initializers), and
disappears afterward. balance is the real property that sticks around; this is a deliberate
pattern: validate the raw parameter, then store it (or a derived value) as a property.
require(condition) { "message" } throws IllegalArgumentException with that message when
condition is false -- it's the standard way to guard a constructor, and reads better than a
hand-written if (!condition) throw ....
Full program: examples/02_init_blocks.kt.
Done here? The practice set for Part 7 — including the solutions — is on the part page.