【问题标题】:Mixed-in object variables available in mixed-in role declaration混合角色声明中可用的混合对象变量
【发布时间】:2018-06-15 23:28:24
【问题描述】:

我想知道如何在运行时将抽象角色混合到变量中。这是我想出的

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']"; } };

但是,这会引发(完全合理的)错误:

$ 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

$!word 属于该类,因此在 mixin 声明中因此不可用。但是,but is simply a function call 所以声明的变量应该在内部可用,对吧?访问它的正确语法是什么?

【问题讨论】:

    标签: class mixins raku


    【解决方案1】:

    正确的语法是$.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")
    

    希望这会有所帮助。

    【讨论】:

    • 您可以使用抽象角色jsonable(例如,能够在类型检查中使用它),并使用匿名角色实现它:my $that-word = (Bare-Word.new( "Hola" ) but role { method to-json() { return "['$.word']"; } }) but jsonable;
    猜你喜欢
    • 2018-11-07
    • 1970-01-01
    • 2015-12-31
    • 2017-09-23
    • 2011-02-23
    • 2017-04-09
    • 1970-01-01
    • 2016-09-17
    • 1970-01-01
    相关资源
    最近更新 更多