将角色混合到可调用对象中



理论上,您可以在运行时将角色混合到对象中。所以我正在尝试使用一个函数来做到这一点:

my &random-f = -> $arg  { "Just $arg" };
say random-f("boo");
role Argable {
method argh() {
self.CALL-ME( "argh" );
}
}
&random-f does Argable;
say random-f.argh;

在角色中,我使用self来引用已定义的函数,CALL-ME实际调用角色中的函数。但是,这会导致以下错误:

Too few positionals passed; expected 1 argument but got 0
in block <unit> at self-call-me.p6 line 5

我真的不知道谁期待 1 个论点。从理论上讲,它应该是CALL-ME功能,但谁知道呢。消除self.会产生不同的错误:CALL-ME used at line 11。将does Callable添加到Argable(将 self 放回后(会导致相同的错误。这能做到吗?知道怎么做吗?

代码中有两处不正确:

say random-f.argh;  # *call* random-f and then call .argh on the result

您想在Callable上呼叫.argh,以便:

say &random-f.argh;

其次,您应该能够调用self:您可以在.argh方法的签名中调整它:

method argh(&self:) {

所以最终的代码变成:

my &random-f = -> $arg  { "Just $arg" };
say random-f("boo");
role Argable {
method argh(&self:) {
self( "argh" );
}
}
&random-f does Argable;
say &random-f.argh;

最新更新