Start learning free

LESSON 65 OF 70 · PROJECTS: OBJECT-ORIENTED

Bank Account in Scala: Encapsulation with a Private Balance

Practice Read the full explanation

Build a BankAccount class that keeps its balance private and lets other code change it only through methods that check the rules. This is encapsulation: the object protects its own data.

Private balance. Declare private var balance: Double = initialBalance inside the class, so only the class can change it.

What the class must have (Scala):

  • The primary constructor class BankAccount(initialBalance: Double): creates an account that starts with the given balance.
  • def deposit(amount: Double): Unit: adds amount to the balance. If amount is zero or negative, do nothing (no error, the balance stays the same).
  • def withdraw(amount: Double): Boolean: if amount is zero or negative, or larger than the balance, change nothing and return false. Otherwise subtract it from the balance and return true. Withdrawing exactly the whole balance is allowed (the balance becomes 0).
  • def getBalance(): Double: returns the current balance. It is the only way for outside code to read it.

Scala's Double prints as 120.0, so the driver uses .toInt to print 120.

The driver. The driver at the end of the starter code is already written and uses your class. It runs these checks:

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")
        }
    }
}

Walk through it: start with 100, deposit 50 (150), withdraw 30 (120), withdraw 200 is refused (still 120). Then deposit -20, deposit 0 and withdraw -5 are all ignored (still 120). Withdrawing 120 succeeds and empties the account, so the balance is 0, and withdrawing 1 more is refused.

Expected output:

Balance: 120
Balance: 120
Withdrew all
Balance: 0
Rejected

Both deposit and withdraw start with a guard that rejects amount <= 0. Write the guard first, then the change to the balance.

private var balance: Double = initialBalance inside the class body.

if (amount <= 0 || amount > balance) return false, then balance -= amount and return true.

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")
        }
    }
}

STEP 1 OF 11
    Ctrl + Enter to check

    SCALA · PROJECTS: OBJECT-ORIENTED

    Bank Account in Scala, explained

    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): Unit adds to the balance, but ignores amounts that are zero or negative.
    • withdraw(amount: Double): Boolean takes money out and returns true. It changes nothing and returns false when the amount is zero or negative, or larger than the balance. Withdrawing exactly the whole balance is allowed.
    • getBalance(): Double is 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

    1. Declare the class with initialBalance in its header. This is the primary constructor, and BankAccount(100.0) in the driver calls it.
    2. 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 a var because it changes, and private keeps it hidden.
    3. Start deposit with an amount parameter and a Unit result: a deposit changes the account and gives no answer back.
    4. Guard against bad amounts: a one-line if with a return when amount is zero or less.
    5. Add the amount to balance. Only positive amounts get past the guard.
    6. Start withdraw with the same parameter but a Boolean result, so the caller learns whether the money left.
    7. Refuse bad requests: return false when the amount is not positive, or when it is more than the balance. The comparison is amount > balance, so asking for exactly the balance is not refused.
    8. Subtract the amount from the balance.
    9. Return true: reaching this line means the withdrawal happened.
    10. Add getBalance with no parameters and a Double result, and return balance. 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

    • return in a method. In Scala the last expression of a block is its value, so a method can end with just balance and no return. An early exit from the middle of a method does need return, 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): Unit says the method gives back nothing useful. A method that uses return needs its result type written out, which is why every method here has one.
    • Printing a Double. println(120.0) prints 120.0. The driver calls .toInt, which drops the fractional part, to print 120.
    • private means private to the class. Code in the class's methods can use balance freely; code outside cannot, as the compiler message above shows.

    Edge cases and common mistakes

    • Withdrawing the whole balance. Using amount >= balance in 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, not amount < 0. For withdraw, a request for 0 returns false.
    • Returning something from deposit. The method returns Unit. 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 Double stores most decimal fractions approximately. Ten deposits of 0.1 give a balance of 0.9999999999999999, so withdraw(1.0) then returns false. 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:

    StartCallResult
    50.0withdraw(-5.0)false
    50.0withdraw(50.01)false
    50.0withdraw(50.0)true, balance 0.0
    10.0withdraw(0.0)false

    Key takeaways

    • A private var keeps state inside the class, so the methods control every change.
    • Guard clauses reject bad input first and keep the main logic short.
    • A Boolean result lets a method report whether it did its job.
    Keep going with Scala1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free