Course of Raku / Addendum 🆕 / Types and text machines / Objects and classes / Exercises / A bank account

Solution: A bank account

Here is a possible solution to the task.

Code

class Account {
    has $.balance = 0;

    method deposit($amount) {
        $!balance += $amount;
    }

    method withdraw($amount) {
        if $amount > $!balance {
            say 'declined: insufficient funds';
        }
        else {
            $!balance -= $amount;
        }
    }
}

my $account = Account.new;
$account.deposit(100);
$account.withdraw(30);
$account.withdraw(200);

say $account.balance;

🦋 You can find the source code in the file bank-account.raku.

Output

declined: insufficient funds
70

Comments

  1. has $.balance = 0 gives a public read accessor and a starting value. Inside the methods the attribute is updated through its private name $!balance.

  2. The second withdrawal asks for more than the balance, so it is declined and the balance stays at 70.

Course navigation

A bank account   |   Shapes sharing a role