Course of Raku / Objects, I/O, and exceptions / Classes and objects / Roles / Exercises / A named, aged pet

Solution: A named, aged pet

Here is a possible solution to the task.

Code

role Named {
    method label {
        'I am ' ~ self.name;
    }
}

role Aged {
    method status {
        self.age ~ ' years';
    }
}

class Pet does Named does Aged {
    has $.name;
    has $.age;
}

my $p = Pet.new(name => 'Rex', age => 3);
say $p.label;
say $p.status;

🦋 You can find the source code in the file named-aged-pet.raku.

Output

I am Rex
3 years

Comments

  1. Pet composes two roles at once, gaining both the label and the status methods.

  2. Each role’s method uses an attribute (name or age) that the Pet class provides.

Course navigation

A named, aged pet   |   A dancing robot