Recap - Bank Account
Part of the Object Oriented Programming section of Coddy's Kotlin journey. Lesson 11 of 57.
Challenge
MediumComplete the class BankAccount(val owner: String, opening: Int). Its init block requires a non-blank owner (owner is empty) and a non-negative opening deposit (opening must not be negative). balance has a private setter. Transactions are kept in a private MutableList and exposed as val transactions: List<String>. deposit(amount) and withdraw(amount) return true on success: amounts below 1 are refused, and a withdrawal larger than the balance is refused; successful changes are recorded as +50 or -20. statement() returns Ada: 30 (+50, -20) or Ada: 0 (no transactions).
The supplied code reads the owner and opening deposit (name,amount), then commands d n or w n. It prints refused for failed commands, and finally the statement; an invalid account prints the error message.
Your code goes in BankAccount.kt. Main.kt holds the supplied input/output code and cannot be edited.
Try it yourself
fun main() {
// Supplied input/output code: keep it as it is
val input = generateSequence(::readLine).toList()
try {
val (name, amount) = input[0].split(",")
val account = BankAccount(name, amount.toInt())
for (cmd in input.drop(1)) {
val (op, n) = cmd.split(" ")
val ok = if (op == "d") account.deposit(n.toInt()) else account.withdraw(n.toInt())
if (!ok) println("refused")
}
println(account.statement())
} catch (e: IllegalArgumentException) {
println(e.message)
}
}
All lessons in Object Oriented Programming
1Classes and Objects
Working With FilesDefining ClassesPrimary Constructorsinit Blocks and ValidationSecondary ConstructorsRecap - Library Card4Inheritance
Open Classes and SubclassesOverriding Memberssuper and ConstructorsAbstract ClassesRecap - Staff Directory2Properties and Encapsulation
Custom AccessorsVisibility ModifiersPrivate Setterslazy and lateinitRecap - Bank Account5Interfaces
Declaring InterfacesDefault MethodsMultiple InterfacesInterfaces as TypesRecap - Payment Methods8Generics
Generic FunctionsGeneric ClassesType ConstraintsVariance With in and outRecap - Priority Queue11Project: Library Management
Books and MembersBorrowing BooksPractice on your own: Kotlin playground