In Glossary§

See primary documentation in context for Roles

Roles, mix-ins or traits define interfaces and/or implementation of those interfaces as well as instance variables using them, and are mixed-in when declaring classes that follow that interface. Abstract classes are particular examples of Roles where the actual implementation is deferred to the class that uses that Role.

Roles are part of Raku's object system, and are declared using the role keyword and used in class declaration via does.

In Object orientation§

See primary documentation in context for Roles

Roles are a collection of attributes and methods; however, unlike classes, roles are meant for describing only parts of an object's behavior; this is why, in general, roles are intended to be mixed in classes and objects. In general, classes are meant for managing objects and roles are meant for managing behavior and code reuse within objects.

Roles use the keyword role preceding the name of the role that is declared. Roles are mixed in using the does keyword preceding the name of the role that is mixed in.

Roles can also be mixed into a class using is. However, the semantics of is with a role are quite different from those offered by does. With is, a class is punned from the role, and then inherited from. Thus, there is no flattening composition, and none of the safeties which does provides.

constant ⲧ = " " xx 4#Just a ⲧab 
role Notable {
    has Str $.notes is rw;
 
    multi method notes() { "$!notes\n" };
    multi method notesStr $note ) { $!notes ~= "$note\n" ~ ⲧ };
 
}
 
class Journey does Notable {
    has $.origin;
    has $.destination;
    has @.travelers;
 
    method Str { "⤷ $!origin\n" ~ ⲧ ~ self.notes() ~ "$!destination ⤶\n" };
}
 
my $trip = Journey.new:origin<Here>:destination<There>,
                        travelers => <þor Freya> );
 
$trip.notes("First steps");
notes $trip: "Almost there";
print $trip;
# OUTPUT: 
#⤷ Here 
#       First steps 
#       Almost there 
# 
#There ⤶ 

Roles are immutable as soon as the compiler parses the closing curly brace of the role declaration.