perl6 – 覆盖角色的属性

前端之家收集整理的这篇文章主要介绍了perl6 – 覆盖角色的属性前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
是否可以覆盖角色的属性以提供默认值?
role A {
     has $.a;
}
class B does A {
    has $.a = "default";
}
my $b = B.new;

这会导致编译错误

===SORRY!=== Error while compiling:
Attribute '$!a' already exists in the class 'B',but a role also wishes to compose it

解决方法

由于R中的方法可能引用$!a,因此会引起含糊不清的属性.

使用子方法BUILD初始化inherited / mixedin属性.

role R { has $.a };
class C does R {
    submethod BUILD { $!a = "default" }
};
my $c = C.new;
dd $c;
# OUTPUT«C $c = C.new(a => "default")␤»

根据您的用例,您最好通过角色参数设置默认值.

role R[$d] { has $.a = $d };
class C does R["default"] { };
my $c = C.new;
dd $c;
# OUTPUT«C $c = C.new(a => "default")␤»
原文链接:https://www.f2er.com/Perl/241742.html

猜你在找的Perl相关文章