Possible to add method to Rect with "Extension" ?

About Monkey 2 Forums Monkey 2 Programming Help Possible to add method to Rect with "Extension" ?

Tagged: 

This topic contains 7 replies, has 6 voices, and was last updated by  codifies 2 years, 5 months ago.

Viewing 8 posts - 1 through 8 (of 8 total)
  • Author
    Posts
  • #4413

    Diffrenzy
    Keymaster

    Is it possible to add a method to Rect, by the means of the Extention keyword/functionality?

    If yes, please post an example, because my attemts results in compiler errors. 🙂

    #4425

    Mark Sibly
    Keymaster

    Here you go..

    Actually took me a few attempts to get right – you should be able to use plain ‘Rect’ inside the extension instead of ‘Rect<T>’ (the way you can inside normal class decls) but that’s not working. Will look into it eventually, but Rect<T> will always work.

    #4426

    wiebow
    Participant

    OK. Why would you want to use Extension instead of Extends?  Can someone explain the rationale behind it?

    #4427

    Mark Sibly
    Keymaster

    OK. Why would you want to use Extension instead of Extends?

    The main advantage of extensions is that they can be used with objects that you *didn’t* create. With inheritance, you need to be in control of the ‘new’ that creates the object.

    So the above ‘Grow’ extension can be used with any Rect, not just ‘MyRects’ or some other class that Extends Rect. (also, you can’t currently extend structs anyway but that’s not really the point here!).

    You can do all sorts of cool things with extensions, like add a DrawMysprite() method to canvas, To:String() or To:JsonValue() to *anything* etc.

    There can also be multiple extensions of the same class, as opposed to single inheritance where you can create a new CoolRect1 or a CoolRect2 – but not both.

    It’s important to note that extension methods are really just global functions (which is why I was a bit wary of adding them in the first place). But in mx2, some functionality can only be achieved via methods, eg: operators, To:String() etc, so they provide quite a nice way of dealing with that.

    #4475

    Diffrenzy
    Keymaster

    Great, thanks for showing how 🙂

    #5197

    seyhajin
    Participant

    Hi,

    I need to extend Vec2<T> struct with additionnal features but i have an errors with ‘Property’. Can you tell me if my code is correct and why he doesn’t work?

    #5251

    cocon
    Participant

    Doing some tests…

    #5262

    codifies
    Participant

    trouble using extern classes with any kind of extention

    using either extends or extention I get Error : Super class ‘default.Rect’ has no default constructor
    there is a slight complication in that the only a (float,float) constructor, but it will say the same if there is a () constructor…

Viewing 8 posts - 1 through 8 (of 8 total)

You must be logged in to reply to this topic.