perl6 – 覆盖角色的属性
发布时间:2020-12-15 22:07:01 所属栏目:大数据 来源:网络整理
导读:是否可以覆盖角色的属性以提供默认值? 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 com
是否可以覆盖角色的属性以提供默认值?
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")?? (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |