How do you add a method to an existing class in Perl 6?

后端 未结 4 1884
太阳男子
太阳男子 2021-02-19 04:40

The Int class has a method is_prime, so I figured, just for giggles, I\'d like to add some other methods to Int for some of my hobby projects that do n

4条回答
  •  误落风尘
    2021-02-19 05:37

    Huh, this works, which I thought I'd tried before and I like better than what I presented in the question.

    Int.^add_method( 'is-even', method () returns Bool:D {
        return False if self % 2;
        return True;
        } );
    
    say 137.is-even;
    

    I'm not sure this should work, though. The add_method docs says we should only do this before the type is composed. If I call Int.^methods the is-even doesn't show up. Still, it seems to be callable and doing the right thing.

    Lexical methods

    Playing more, I figured I could make a method that's not attached to any class and call that on an object:

    my &is-even = method (Int:D :) returns Bool:D { self %% 2 };
    

    This constructs a Callable (look at &is-even.WHAT). In the signature, I constrain it to be a definite Int value (Int:D) but don't give it a name. I add the colon after type constraint to note that the first argument is the invocant. Now I can apply that method to any object I like:

    say 137.&is-even;
    say 138.&is-even;
    say "foo".&is-even;  # works, although inside is-even blow up
    

    This is nice in a different dimension since it's lexical, but not nice in that an object of the wrong type might call it. The error shows up after it thinks it has the method to dispatch to.

提交回复
热议问题