BackPacker777
BackPacker777

Reputation: 683

Can I overload methods in Moose?

I am looking for a solution similar to Java's whereby I can create methods with the same name but with different parameter lists.

e.g.

method makeDeposit() {
    system("cls");
    print "How much money do you want to deposit?: ";
    chomp (my $amount = <STDIN>);
    $self->insufficientFunds(0);
    $self->balance($self->balance() + $amount);
    $self->performBalanceInquiry();
    return;
}

method makeDeposit(Int $amount) {
    $self->insufficientFunds(0);
    $self->balance($self->balance() + $amount);
    $self->performBalanceInquiry();
    return;
}

Thanks!

Upvotes: 2

Views: 275

Answers (2)

ikegami
ikegami

Reputation: 385897

You can check how many args were passed by checking the length of @_

sub makeDeposit {
    my $amount;
    if (@_) {
       ($amount) = @_;
    } else {
        system("cls");
        print "How much money do you want to deposit?: ";
        chomp($amount = <STDIN>);
    }

    $self->insufficientFunds(0);
    $self->balance($self->balance() + $amount);
    $self->performBalanceInquiry();
}

Often, as is the case here, it's simpler to check if the parameter is defined.

sub makeDeposit {
    my ($amount) = @_;
    if (!defined($amount)) {
        system("cls");
        print "How much money do you want to deposit?: ";
        chomp($amount = <STDIN>);
    }

    $self->insufficientFunds(0);
    $self->balance($self->balance() + $amount);
    $self->performBalanceInquiry();
}

Note that your example shows an inappropriate division of concerns. Different modules should be handling IO and the account.

Upvotes: 4

amon
amon

Reputation: 57630

Perl is a rather loosely typed language, and the (pseudo)-type names in method signatures are just a shorthand for dynamic input validation code.

However, in the infinite lands of CPAN there lives the module MooseX::MultiMethods which will allow you to do what you want—but you have to prefix your methods with the multi keyword.

E.g.

multi method makeDeposit() { ... }
multi method makeDeposit(Int $amount) { ... }

Upvotes: 7

Related Questions