覆盖角色的属性

J H*_*all 6 perl6

是否可以覆盖角色的属性以提供默认值?

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)

  • "由于R中的方法可能引用$!a,所以会引用含糊不清的属性." 这是在谈论为什么OP的方法无法工作,或者即使你的第一个解决方案可能出现的问题,以及你的第二个解决方案(使用参数角色)解决了什么? (2认同)