Thursday, October 9, 2008

Typesafe ActionScript Enums

A busy week, with some client work and a 4-day weekend away (starting in about 12 hours, woot!), so a quick post.

Typesafe Enums are something we take for granted these days in a lot of programming languages, but unfortunately ActionScript isn't yet one of them. However, there are a few solutions out there to provide this functionality, and of course since none of them met my needs exatly, this is mine!

First, let's jump into how we use the damn things - here's how you would create a new Enum type:

package demo
{
    import info.joshmcdonald.barra.utils.Enum;

    public class CompassPoint extends Enum
    {
        public static const NORTH      : CompassPoint = Enum.create(CompassPoint, "N",  "Towards Santa");
        public static const NORTH_EAST : CompassPoint = Enum.create(CompassPoint, "NE", "North East");
        public static const EAST       : CompassPoint = Enum.create(CompassPoint, "E",  "East");
        public static const SOUTH_EAST : CompassPoint = Enum.create(CompassPoint, "SE", "South East");
        public static const SOUTH      : CompassPoint = Enum.create(CompassPoint, "S",  "Towards Penguins");
        public static const SOUTH_WEST : CompassPoint = Enum.create(CompassPoint, "SW", "South West");
        public static const WEST       : CompassPoint = Enum.create(CompassPoint, "W",  "West");
        public static const NORTH_WEST : CompassPoint = Enum.create(CompassPoint, "NW", "North West").close();
    }
}

Seems simple enough, right?

Wait, hold on, "what the hell is that on the end?" I hear you cry? Why, I'm terribly glad you asked! That my friends, combined with using Enum.create() is how we stop people from instantiating new instances willy-nilly, which of course leads to anarchy! When you call close(), no more instances of Compass can be instantiated, and if you try, you'll get a run-time error.

Now, some "client" code that makes use of our new CompassPoint class:

<mx:Script>
    <![CDATA[
        import info.joshmcdonald.barra.utils.Enum;
        import demo.CompassPoint;

        private function cc() : void
        {
            var towardsPerth : CompassPoint = CompassPoint.SOUTH_WEST;

            trace("Direction to Perth is", towardsPerth);

            trace("What are all the Compass points?");
            trace("   * " + Enum.valuesOf(CompassPoint).join("\n   * "));
        }

    ]]>
</mx:Script>
</mx:Application>

As usual, I've added Enum.as to my blog's google code repository.

Next week: Skinning with Degrafa!

0 comments:

This is

  • Tales of Flex
  • From Brisbane, Australia
  • Opinions on Flex development
  • Tips and FAQs
  • Shameless self-promotion

I am

  • Twitterer
  • Flexcoder
  • Maroon
  • Designer
  • Java lover
  • That loud-mouthed Aussie yob
  • Blogger
  • Problem solver
  • Contributor
  • Cricket Fan
  • Lousy photographer
  • Great cook

I read



Subscribe via RSS to receive updates!