理论上,你可以mix in a role into an object in runtime。所以我试图用一个函数来做这个:
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
我真的不知道谁会期待一个论点。从理论上讲,它应该是CALL-ME
函数,但谁知道呢。消除self.
会产生不同的错误:CALL-ME used at line 11
。将does Callable
添加到Argable
(放回自我后)会导致相同的错误。可以这样做吗?怎么想?
答案 0 :(得分:6)
您的代码中有两件事不正确:
say random-f.argh; # *call* random-f and then call .argh on the result
您想在.argh
上致电Callable
,所以:
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;