是否可以覆盖角色的属性以提供默认值?
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")»