Roles
A role is a reusable
unit
of class code. Much like a module exports subroutines into your
program or another module, a role exports methods and attributes into
a class. If your first thought on reading this is
“Isn’t that just
inheritance?”, then welcome to a whole new world.
Inheritance is one way to reuse code, but many relationships other
than isa
are possible. Various languages pick an
alternative and provide syntax for it: Ruby has
mixins
,
Java has
interfaces
,
and some versions of Smalltalk have
traits
.
Perl roles go a bit beyond all of them.
You define a role using the
role
keyword:
role Hitchhiker { . . . }
You pull a role into a class using the does
keyword:
class Arthur does Hitchhiker { . . . }
Roles cannot instantiate objects directly. To create an object that
makes use of a role, you make a new
object from a
class that uses that role:
$person = Arthur.new( . . . );
Composition
Like classes, roles can define both attributes and methods:
role Hitchhiker { has $.towel; method thumb_ride ($self: $ship) { . . . } . . . }
Unlike classes, when you pull a role’s methods and
attributes into a class they aren’t maintained in an
inheritance hierarchy to be searched later. Instead, they are
composed into the class almost as if they had been defined in that
class. All methods defined in the role are accessible in the composed
class, even if they wouldn’t be inherited. All
attributes defined in the role are accessible in the composed class
by their direct $.name
, not just by their ...
Get Perl 6 and Parrot Essentials, Second Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.