| Roles take the place of all of these: - Java interfaces - abstract classes - C++ templates - Python mixins - Smalltalk traits So are you telling me that you haven't used any of those? --- Roles combine all of those features very simply. role Interface {
method hello-world ( --> Str ) {...}
# the ... means it needs to be implemented by consuming class
}
role Abstract {
has Str $.name is required;
# adds an accessor method of the same name
method greet ( --> Str ) {...}
}
role Template[ Real ::Type, Type \initial-value ] {
has Type $!value = initial-value;
method get ( --> Type ) {
$!value
}
method set ( Type \new-value ) {
$!value = new-value
}
}
my $value = 42 but anon role Mixin {
method Str ( --> 'Life, the Universe and Everything' ){
}
}
Roles were heavily influenced by Smalltalk traits. Rather than being limited to those uses, Roles were expanded to include all of those other
use-cases as well.--- Really Roles are a better method of code-reuse than inheritance. role Animal {
method species ( --> Str ){...}
method produces-egg ( --> Bool ){...}
}
role Mammal does Animal {
method produces-egg ( --> False ){
# most mammals do not produce eggs.
}
}
role Can-Fly {
method flap-wings ( --> 'flap flap' ){
}
}
class Bat does Mammal does Can-Fly {
method species ( --> 'Bat' ){
}
}
class Bird does Animal does Can-Fly {
method species ( --> 'Bird' ){
}
method produces-egg ( --> True ) {
}
}
class Platypus does Mammal {
method species ( --> 'Platypus' ){
}
method produces-egg ( --> True ) {
# override Mammal.produces-egg()
}
}
Of course a simple example doesn't do this ability justice. It really shines on large code-bases.For a better example see: “Curtis Poe (Ovid) - Roles versus Inheritance” https://www.youtube.com/watch?v=cjoWu4eq1Tw That is of course about roles in Perl, which doesn't have all the same features. All of the points do apply to Raku roles though. --- Raku has so many good ideas it would be a waste if other languages didn't copy at least some of them. I of course can understand if a single language doesn't want to copy all of them at the same time. It would definitely be a waste if no other language tries to combine regular expressions, parsers, and objects like Raku grammars have done. At the very least Raku regular expressions are easier to understand than Perl compatible regular expressions. (Note that I very much DO understand PCRE syntax, having used it heavily in Perl for many years.) Compare the Raku grammar for JSON https://modules.raku.org/dist/JSON::Tiny:cpan:MORITZ/lib/JSO... to the Perl version https://metacpan.org/release/JSON-Decode-Regexp/source/lib/J... I would like to point out that when JSON started allowing any value as a top-level result, it actually made the Raku code simpler. https://github.com/moritz/json/commit/9888329771730574967197... |