Mixing roles into callables

帅比萌擦擦* 提交于 2019-12-10 14:49:59

问题


Theoretically, you can mix in a role into an object in runtime. So I am trying to do this with a function:

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;

Within the role, I use self to refer to the already defined function, and CALL-ME to actually call the function within the role. However, this results in the following error:

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

I really have no idea who's expecting 1 argument. Theoretically, it should be the CALL-ME function, but who knows. Eliminating the self. yields a different error: CALL-ME used at line 11. Adding does Callable to Argable (after putting self back) results in the same error. Can this be done? Any idea of how?


回答1:


There's two things incorrect in your code:

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

You want to call .argh on the Callable so:

say &random-f.argh;

Secondly, you should just be able to call self: you can tweak this in the signature of the .argh method:

method argh(&self:) {

So the final code becomes:

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;


来源:https://stackoverflow.com/questions/50578740/mixing-roles-into-callables

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!