是否可以覆盖角色的属性以提供默认值?
role A {
has $.a;
}
class B does A {
has $.a = "default";
}
my $b = B.new;
Run Code Online (Sandbox Code Playgroud)
这会导致编译错误:
===SORRY!=== Error while compiling:
Attribute '$!a' already exists in the class 'B', but a role also wishes to compose it
Run Code Online (Sandbox Code Playgroud)
小智 5
由于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")?»
Run Code Online (Sandbox Code Playgroud)
根据您的用例,您最好通过角色参数设置默认值.
role R[$d] { has $.a = $d };
class C does R["default"] { };
my $c = C.new;
dd $c;
# OUTPUT«C $c = C.new(a => "default")?»
Run Code Online (Sandbox Code Playgroud)