simo
simo

Reputation: 24590

How to attach a property to string?

Can I do something like this in haxe:

trace ("Blue".description);
trace ("Green".description);
trace ("Red".description);

then, somewhere add a switch based on string value to return different description for each case?

I saw people using this for localization, like "Car".i18()

Any one can help?

Upvotes: 1

Views: 79

Answers (1)

Jason O'Neil
Jason O'Neil

Reputation: 6008

Check out static extensions.

Basically it allows you to pretend static methods are member methods, but the first argument is the object you're operating on.

In your example

class ColorDescriptions {
    static public function description( color:String ) {
        return switch (color) {
            case "red": "passionate";
            case "blue": "calm";
            case "green": "environmentally friendly";
            default: "unknown colour";
        };
    }
}

And then:

using ColorDescriptions; // Use static methods from `ColourDescriptions` as mixins
...
trace( "red".description() ); // "passionate"

This only works with methods/functions, not properties. So "red".description() is possible, but "red".description is not.

Upvotes: 1

Related Questions