Search code examples
perlmoosemoops

How can I overload methods in Moops?


I would like to overload some methods in Moops.

I have the tried the following code:

method setIdNum() {
      print "Please enter ID number: ";
      chomp (my $input = <STDIN>);
      $self->$idNum($input);
}

method setIdNum(Int $num) {
      $self->$idNum($num);
}

But it errors by saying setIdNum is redefined.


Solution

  • If you want multimethods, you have to ask for them explicitly by putting multi in front of the method keyword:

    multi method setIdNum() {
      print "Please enter ID number: ";
      chomp (my $input = <STDIN>);
      $self->$idNum($input);
    }
    
    multi method setIdNum(Int $num) {
      $self->$idNum($num);
    }
    

    You may also need to explicitly ask for Kavorka support inside your class declaration:

    class Whatever {
        use Kavorka qw( multi method );
      ...