Problem overview
The lesson asks for a BankAccount class whose balance cannot be changed from outside. Other code can only ask the account to deposit or withdraw, and the account decides whether the request is allowed. Hiding data behind methods that enforce rules is called encapsulation.
The class needs four members:
- a constructor taking the starting balance as a
Double; deposit(amount), which adds a positive amount and silently ignores zero or negative ones;withdraw(amount): Boolean, which returnsfalseand changes nothing if the amount is not positive or is more than the balance, and otherwise subtracts it and returnstrue;getBalance(): Double, the only way to read the balance.
The driver starts with 100, deposits 50 and withdraws 30, which leaves 120. A withdrawal of 200 is refused. A deposit of -20, a deposit of 0 and a withdrawal of -5 are all ignored. Withdrawing 120 succeeds and empties the account, and one more withdrawal is rejected. The output:
Balance: 120
Balance: 120
Withdrew all
Balance: 0
Rejected
Approach
The balance lives in a private var inside the class. Because it is private, a line such as account.balance = 1000000.0 in the driver does not compile: the compiler says it cannot access the property because it is private in BankAccount. The only paths to the number go through the three methods, and each method checks the rules before touching it.
Both changing methods follow the same pattern: a guard at the top rejects bad input, and the real work happens below it. That keeps each method short and keeps the valid path easy to read.
Step by step
- Declare the class with
initialBalancein its header. This is the primary constructor. - Store the balance. The constructor parameter exists only while the object is being set up, so a property copies it:
private var balance: Double = initialBalance. It is avarbecause deposits and withdrawals change it, andprivatehides it. - Start
deposit. It takes aDoubleamount and returns nothing, so it has no return type. - Guard it. If the amount is zero or less,
returnimmediately. The balance stays as it was. - Add the amount. Only a positive amount gets past the guard.
- Start
withdraw, which returns aBooleanso the caller learns whether the money left. - Refuse bad requests. One
ifcovers both cases: the amount is not positive, or it is larger than the balance. Either one returnsfalse. - Subtract the amount from the balance.
- Return
true. Reaching this line means the guard did not fire. - Add
getBalancewith no parameters and aDoubleresult, and returnbalance.
The solution in Kotlin
class BankAccount(initialBalance: Double) {
private var balance: Double = initialBalance
fun deposit(amount: Double) {
if (amount <= 0) return
balance += amount
}
fun withdraw(amount: Double): Boolean {
if (amount <= 0 || amount > balance) return false
balance -= amount
return true
}
fun getBalance(): Double {
return balance
}
}
class Solution {
fun mainFunction() {
val account = BankAccount(100.0)
account.deposit(50.0)
account.withdraw(30.0)
account.withdraw(200.0)
println("Balance: " + account.getBalance().toInt())
account.deposit(-20.0)
account.deposit(0.0)
account.withdraw(-5.0)
println("Balance: " + account.getBalance().toInt())
if (account.withdraw(120.0)) {
println("Withdrew all")
}
println("Balance: " + account.getBalance().toInt())
if (!account.withdraw(1.0)) {
println("Rejected")
}
}
}
Some details of this Kotlin code deserve a closer look.
Doubles and the literals
The amounts are Double, so the driver writes 100.0, not 100. Kotlin does not convert an Int to a Double on its own. The call BankAccount(100) is a type error.
A Double prints with a decimal point: BankAccount(10.5).getBalance() prints 10.5 and a balance of 120 would print 120.0. That is why the driver calls .toInt(), which drops the fractional part, before printing.
The early return
if (amount <= 0) return works in a function that returns nothing: a bare return leaves it. In withdraw, the same one-line form returns a value, return false, and the compiler checks that every path ends with a Boolean.
Short-circuit evaluation
In amount <= 0 || amount > balance, the second test runs only when the first is false. Either order gives the right answer here, but the guard reads naturally from "is the request even valid" to "can we afford it".
Why a method and not a public property
If balance were public, any code could set it to a negative number and no rule would hold. With the private property and the methods, the invariant "the balance is never negative" can only be broken inside the class, and the class never breaks it.
Edge cases and common mistakes
- Withdrawing the exact balance. The test is
amount > balance, not>=. Withdrawing 120 from 120 succeeds and leaves 0. With>=, the "Withdrew all" line would never print. - Zero and negative amounts.
withdraw(0.0)returnsfalse, and so doeswithdraw(-5.0). A missing guard would let a negative withdrawal increase the balance. - Just over the balance. On an account with 100.0,
withdraw(100.01)returnsfalseandwithdraw(100.0)then returnstrue. - Forgetting the guard in deposit. A deposit of -20 would quietly lower the balance.
- Returning
truetoo early. Subtract first, then returntrue, or the balance never changes.
Key takeaways
- A
private varkeeps outside code away from the data; methods are the only way in. - Each method validates its input in a guard, then changes the state.
- A
Booleanresult tells the caller whether a request was accepted.
