jjm*_*elo 6 class mixins perl6
我想知道如何在运行时将抽象角色混合到变量中.这就是我想出来的
role jsonable {
method to-json( ) { ... }
}
class Bare-Word {
has $.word;
method new ( Str $word ) {
return self.bless( $word );
}
}
my $that-word = Bare-Word.new( "Hola" ) but role jsonable { method to-json() { return "['$!word']"; } };
Run Code Online (Sandbox Code Playgroud)
但是,这会引发(完全合理的)错误:
$ perl6 role-fails.p6
===SORRY!=== Error while compiling /home/jmerelo/Code/perl6/dev.to-code/perl6/role-fails.p6
Attribute $!word not declared in role jsonable
at /home/jmerelo/Code/perl6/dev.to-code/perl6/role-fails.p6:14
------> hod to-json() { return "['$!word']"; } }?;
expecting any of:
horizontal whitespace
postfix
statement end
statement modifier
statement modifier loop
Run Code Online (Sandbox Code Playgroud)
$!word属于类,所以它不可作为这样的混入声明.但是,只是一个函数调用,所以声明的变量应该在里面可用,对吗?访问它的正确语法是什么?
正确的语法将$.word是基本的缩写self.word,因此它使用公共访问方法.
但我认为这里存在一些拼写错误和一些误解.错字(我认为)是.bless只接受命名参数,因此$word它应该是:$word(将位置转换为word => $word).此外,定义但未实现方法,然后使用相同名称来实现具有该名称的角色的角色没有意义.而且我很惊讶它没有产生错误.所以现在摆脱它.这是我的"解决方案":
class Bare-Word {
has $.word;
method new ( Str $word ) {
return self.bless( :$word ); # note, .bless only takes nameds
}
}
my $that-word = Bare-Word.new( "Hola" ) but role jsonable {
method to-json() {
return "['$.word']"; # note, $.word instead of $!word
}
}
dd $that-word; # Bare-Word+{jsonable}.new(word => "Hola")
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助.
| 归档时间: |
|
| 查看次数: |
80 次 |
| 最近记录: |