Course of Raku / Objects, I/O, and exceptions / Classes and objects / Roles
Composing several roles
A class can do more than one role. You simply list each one with its
own does:
role Walk {
method move { 'walking' }
}
role Swim {
method dive { 'diving' }
}
class Duck does Walk does Swim {
}The Duck class now has both the move method
from Walk and the dive method from
Swim:
say Duck.new.move; # walking
say Duck.new.dive; # divingCombining roles like this is called composition. It lets you assemble a class from several independent pieces of behaviour, which is often more flexible than building a single chain of inheritance — a class can mix in exactly the capabilities it needs, and nothing more.
Course navigation
← Roles | Adding a role to an object →
💪 Or jump directly to the
exercises in this section.