Problem overview
You write a class BankAccount that owns a balance and lets the rest of the program change it only through methods that enforce rules. The constructor takes initialBalance, a Double, and the class offers three methods:
deposit(amount: Double): Unitadds to the balance, but ignores amounts that are zero or negative.withdraw(amount: Double): Booleantakes money out and returnstrue. It changes nothing and returnsfalsewhen the amount is zero or negative, or larger than the balance. Withdrawing exactly the whole balance is allowed.getBalance(): Doubleis the only way for outside code to read the balance.
The driver starts with 100, deposits 50 and withdraws 30, which leaves 120. A withdrawal of 200 is refused, so the balance stays 120. A deposit of -20, a deposit of 0 and a withdrawal of -5 are all ignored. Withdrawing 120 then succeeds and empties the account, and withdrawing 1 more is refused. The output is:
Balance: 120
Balance: 120
Withdrew all
Balance: 0
Rejected
Approach: hide the data, guard the methods
Encapsulation means an object protects its own data. If the balance were a public var, any code could write account.balance = 1000000.0 and skip every rule. Marking it private closes that door. Trying to assign to it from outside the class is a compile error:
variable balance cannot be accessed as a member of (a : Acc) from object Main.
private variable balance can only be accessed from class Acc.
Once the field is private, the methods become the only way in, so they are the place for the rules. Both deposit and withdraw use the same pattern, a guard clause: check for the bad cases first and leave at once, then do the real work on the lines below. That keeps the main logic flat and easy to read.
Step by step
- Declare the class with
initialBalancein its header. This is the primary constructor, andBankAccount(100.0)in the driver calls it. - Add
private var balance: Double = initialBalance. The header's parameter is only available while the object is being built and isn't kept as a field here, so this property stores the value. It is avarbecause it changes, andprivatekeeps it hidden. - Start
depositwith anamountparameter and aUnitresult: a deposit changes the account and gives no answer back. - Guard against bad amounts: a one-line
ifwith areturnwhenamountis zero or less. - Add the amount to
balance. Only positive amounts get past the guard. - Start
withdrawwith the same parameter but aBooleanresult, so the caller learns whether the money left. - Refuse bad requests: return
falsewhen the amount is not positive, or when it is more than the balance. The comparison isamount > balance, so asking for exactly the balance is not refused. - Subtract the amount from the balance.
- Return
true: reaching this line means the withdrawal happened. - Add
getBalancewith no parameters and aDoubleresult, and returnbalance. It is a getter: outside code can read the value without being able to change it.
The solution in Scala
class BankAccount(initialBalance: Double) {
private var balance: Double = initialBalance
def deposit(amount: Double): Unit = {
if (amount <= 0) return
balance += amount
}
def withdraw(amount: Double): Boolean = {
if (amount <= 0 || amount > balance) return false
balance -= amount
return true
}
def getBalance(): Double = {
return balance
}
}
class Solution {
def mainFunction(): Unit = {
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")
}
}
}
Scala details
returnin a method. In Scala the last expression of a block is its value, so a method can end with justbalanceand noreturn. An early exit from the middle of a method does needreturn, which is why the guards use it. The lesson also uses it on the last line, which is allowed.- The explicit result type.
def deposit(amount: Double): Unitsays the method gives back nothing useful. A method that usesreturnneeds its result type written out, which is why every method here has one. - Printing a
Double.println(120.0)prints120.0. The driver calls.toInt, which drops the fractional part, to print120. privatemeans private to the class. Code in the class's methods can usebalancefreely; code outside cannot, as the compiler message above shows.
Edge cases and common mistakes
- Withdrawing the whole balance. Using
amount >= balancein the guard would refuse the withdrawal of 120 from 120, and the driver's "Withdrew all" line would never print. The refusal condition is strictly greater than. - Zero amounts. A deposit or withdrawal of 0 is ignored. The guard is
amount <= 0, notamount < 0. Forwithdraw, a request for 0 returnsfalse. - Returning something from
deposit. The method returnsUnit. Ignored deposits are silent, with no error and no result to check. - Changing the balance before checking. Subtracting first and validating after would leave a bad amount applied. The guard must come before any change.
- Making the field public. The driver would still work, but any code could then skip the rules. The point of the lesson is that it can't.
- Decimal rounding. A
Doublestores most decimal fractions approximately. Ten deposits of0.1give a balance of0.9999999999999999, sowithdraw(1.0)then returnsfalse. The lesson only uses whole numbers, so this doesn't show up here, but it matters for any real money handling.
Testing
These small cases cover the rules. Each starts from a fresh account:
| Start | Call | Result |
|---|---|---|
| 50.0 | withdraw(-5.0) | false |
| 50.0 | withdraw(50.01) | false |
| 50.0 | withdraw(50.0) | true, balance 0.0 |
| 10.0 | withdraw(0.0) | false |
Key takeaways
- A
private varkeeps state inside the class, so the methods control every change. - Guard clauses reject bad input first and keep the main logic short.
- A
Booleanresult lets a method report whether it did its job.
