Skip to content

Commit bbd7deb

Browse files
committed
Clarify inheritance vs roles, and non-instance punning (issue #1138)
1 parent ed8e1c8 commit bbd7deb

File tree

1 file changed

+26
-5
lines changed

1 file changed

+26
-5
lines changed

doc/Language/objects.pod6

Lines changed: 26 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -835,8 +835,9 @@ role.
835835
836836
=head2 Inheritance
837837
838-
Roles cannot inherit from classes, but they may cause any class which does
839-
that role to inherit from another class. So if you write:
838+
Roles cannot inherit from classes, but they may carry classes, causing
839+
any class which does that role to inherit from the carried classes.
840+
So if you write:
840841
841842
=begin code
842843
role A is Exception { }
@@ -847,6 +848,21 @@ that role to inherit from another class. So if you write:
847848
then C<X::Ouch> will inherit directly from Exception, as we can see above
848849
by listing its parents.
849850
851+
As they do not use inheritance, roles are not part of the class hierarchy.
852+
Roles are listed with the C<.^roles> meta-method instead. Despite this, a
853+
class or instance may still be tested with smartmatches or type constraints
854+
to see if it does a role.
855+
856+
=begin code
857+
role F { }
858+
class G does F { }
859+
G.^roles.say; # OUTPUT: «((F))␤»
860+
say G ~~ F; # OUTPUT: «True␤»
861+
multi a (F $a) { "F".say }
862+
multi a ($a) { "not F".say }
863+
a(G); # OUTPUT: «F␤»
864+
=end code
865+
850866
=head2 Pecking order
851867
852868
A method defined directly in a class will always override definitions from
@@ -879,22 +895,27 @@ multi-method.
879895
880896
=head2 Automatic Role Punning
881897
882-
Any attempt to directly instantiate a role, as well as many other operations
883-
on it, will automatically create an instance of a class with the same name as
884-
the role, making it possible to transparently use a role as if it were a class.
898+
Any attempt to directly instantiate a role or use it as a type object
899+
will automatically create a class with the same name as the role,
900+
making it possible to transparently use a role as if it were a class.
885901
886902
=begin code
887903
role Point {
888904
has $.x;
889905
has $.y;
890906
method abs { sqrt($.x * $.x + $.y * $.y) }
907+
method dimensions { 2 }
891908
}
892909
say Point.new(x => 6, y => 8).abs; # OUTPUT «10␤»
910+
say Point.dimensions; # OUTPUT «2␤»
893911
=end code
894912
895913
We call this automatic creation of classes I<punning>, and the generated class
896914
a I<pun>.
897915
916+
Punning is not caused by most L<meta-programming|/language/mop> constructs,
917+
however, as those are sometimes used to work directly with roles.
918+
898919
X<|Parameterized Roles>
899920
=head2 Parameterized Roles
900921

0 commit comments

Comments
 (0)