Course of Raku / Objects, I/O, and exceptions / Classes and objects

Roles

A role is a bundle of behaviour (and sometimes data) that can be shared by several classes. Where inheritance says a class is a kind of another, a role describes something a class can do.

You define a role with the role keyword, much like a class, and you give it to a class with the does trait:

role Greet {
    method hello {
        'Hello from ' ~ self.name;
    }
}

class Person does Greet {
    has $.name;
}

The Person class now has the hello method from the role, as if it were written in the class itself:

say Person.new(name => 'Anna').hello; # Hello from Anna

A class that does a role is recognised as having that role:

say Person.new(name => 'Anna') ~~ Greet; # True

Notice that the role’s hello method uses self.name, even though the role itself has no name attribute. That is fine: the method runs as part of whatever class composes the role, and that class provides name. The next topic shows that a class can take on more than one role at a time.

Topics in this section

Practice

Complete the quiz that covers the contents of this section.

Exercises

This section contains 3 exercises. Examine all the topics of this section before doing the coding practice.

  1. A sized box
  2. A named, aged pet
  3. A dancing robot

Course navigation

Solution: An inherited attribute   |   Composing several roles