正确的语法应该是
$.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")
希望这有帮助。