Search code examples
perlmoose

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!


Solution

  • 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) { ... }