raku

How to do a multiple dispatch (or an alternative) for a single pair?


I really like the syntax of a pair :3melee which means melee => 3. I'd like to do the following:

my Creature $creature .= new(:fire-resist);
$creature.damage: :3melee;
$creature.damage: :3fire;

so that the damage method can be neatly written a-la multiple dispatch. Something like the following (not working code):

class Creature {
    has $.health = 10;
    has $.fire-resist;

    proto method damage (Int :$) { * }

    multi method damage (:$melee) {
        say "Damaging in melee for $melee points";
        $!health -= $melee;
    }

    multi method damage (:$fire) {
        return if $!fire-resist;
        say "Damaging with fire for $fire points";
        $!health -= $fire;
    }
}

This currently uses the (:$melee) method for both calls.


Solution

  • Make the named argument mandatory by postfixing !:

    multi method damage (:$melee!) {
        ...
    }
    multi method damage (:$fire!) {
        ...
    }