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

后端 未结 4 1952
太阳男子
太阳男子 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:34

    There's syntactic sugar for this - augment:

    use MONKEY-TYPING;
    
    augment class Int {
        method is-even() returns Bool:D {
            return False if self % 2;
            return True;
        }
    }
    

    Augmenting a class is considered dangerous for two reasons: First, action at a distance, and second, because (as far as I'm aware), there's potential for undefined behaviour deoptimization as it might leave various method caches in an invalid state.

    Thus, the requirement for providing the MONKEY-TYPING pragma before you're allowed to use it.

    As an aside, note that is-even could be written more compactly as self %% 2.

提交回复
热议问题