gpt4 book ai didi

raku - 覆盖角色的属性

转载 作者:行者123 更新时间:2023-12-04 14:41:12 24 4
gpt4 key购买 nike

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

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 初始化继承/混合属性。

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")␤»

关于raku - 覆盖角色的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38816496/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com