@@ -835,8 +835,9 @@ role.
835
835
836
836
= head2 Inheritance
837
837
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:
840
841
841
842
= begin code
842
843
role A is Exception { }
@@ -847,6 +848,21 @@ that role to inherit from another class. So if you write:
847
848
then C < X::Ouch > will inherit directly from Exception, as we can see above
848
849
by listing its parents.
849
850
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
+
850
866
= head2 Pecking order
851
867
852
868
A method defined directly in a class will always override definitions from
@@ -879,22 +895,27 @@ multi-method.
879
895
880
896
= head2 Automatic Role Punning
881
897
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.
885
901
886
902
= begin code
887
903
role Point {
888
904
has $.x;
889
905
has $.y;
890
906
method abs { sqrt($.x * $.x + $.y * $.y) }
907
+ method dimensions { 2 }
891
908
}
892
909
say Point.new(x => 6, y => 8).abs; # OUTPUT «10»
910
+ say Point.dimensions; # OUTPUT «2»
893
911
= end code
894
912
895
913
We call this automatic creation of classes I < punning > , and the generated class
896
914
a I < pun > .
897
915
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
+
898
919
X < |Parameterized Roles >
899
920
= head2 Parameterized Roles
900
921
0 commit comments