Types, classes & roles

Runtime mixins & role requirements

Full

Add a role to a single object at runtime with but, and require methods with a stub.

Beyond composing roles into a class (Roles), a role can be mixed into one object at runtime, and a role can require the composing class to supply a method.

Required methods #

A method body of { ... } (the "stub", yada-yada) declares a method the composing class must provide — an interface contract.

role R { method needed { ... } }
class C does R { method needed { "done" } }
say C.new.needed;
Output
done

Runtime mixin with but #

$value but Role produces a new object that has the role's methods, without changing the original type — the value still behaves as itself otherwise.

role Barks { method speak { "Woof" } }
my $x = 42 but Barks;
say $x.speak;
say $x + 1;
Output
Woof
43

$x gained .speak yet is still an Int for arithmetic ($x + 1 is 43).

Notes #