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 yearsComments
Petcomposes two roles at once, gaining both thelabeland thestatusmethods.Each role’s method uses an attribute (
nameorage) that thePetclass provides.