-->

Mixing roles into callables

2019-06-21 08:28发布

问题:

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;


标签: mixins perl6