Course of Raku / Objects, I/O, and exceptions / Classes and objects / Roles / Exercises / A sized box
Solution: A sized box
Here is a possible solution to the task.
Code
role Sized {
method describe {
'size is ' ~ self.size;
}
}
class Box does Sized {
has $.size;
}
my $b = Box.new(size => 10);
say $b.describe;
say $b ~~ Sized;🦋 You can find the source code in the file greetable.raku.
Output
size is 10
TrueComments
The role provides the
describemethod, and the class composes it withdoes Sized. The method relies onself.size, which is supplied by theBoxclass — the role and the class fit together to form the complete object.Because
Boxdoes the role, the smartmatch$b ~~ SizedisTrue: an object is recognised as having every role its class composes, which is useful for checking what an object can do before calling a role’s method.
Course navigation
← A sized box | A named, aged pet →