Roll your own Enum in Flex

One of the few annoyances I've come across with Flex is ActionScript's lack of support for some common OO constructs like abstract classes, private constructors and enums. 

Creating your own enum class, which gives you compile-time type safety, is pretty trivial:

public class MyEnum{
public static const SOMETHING:MyEnum = new MyEnum("SOMETHING");
public static const SOMETHING_ELSE:MyEnum = new MyEnum("SOMETHING_ELSE");
public var enumName:String;
public function MyEnum(name:String){
enumName = name;
}
}

You then use it as expected:

public class myClass{
public function myClass(enum:MyEnum){...}
}
public class myOtherClass{
...
var mc:MyClass = new MyClass(MyEnum.SOMETHING);
}

You could of course forgo the enumName property and still get type safety. However when debugging it's handy to be able easily see the name of the enum, which the property allows.

Some quick Googling will turn up a raft of different ways to do this - many of them implementing an Enum base class that you can extend. I'm quite happy with my simple solution though - 3 lines of code in each enum class is not too onerous.

comments powered by Disqus