From C++ to ActionScript, Chapter 2: Doh! Enumerated Types Simplified

In an earlier post I proposed a way to implement enumerated types as singleton classes in ActionScript, based on a single class written by Darron Schall, and showed a perl script to generate them. Well, I’ve realized it was unnecesarily complicated. All the values the class methods are returning are just integers, so why not just return them without bothering to create an instance?

Here’s a class that does the job with no instance and no variables:

class DaysOfWeek extends Object
{
public static function get Sunday ():Number { return 0; }
public static function get Monday ():Number { return 1; }
public static function get Tuesday ():Number { return 2; }
public static function get Wednesday ():Number { return 3; }
public static function get Thursday ():Number { return 4; }
public static function get Friday ():Number { return 5; }
public static function get Saturday ():Number { return 6; }

private function DaysOfWeek() {}
}

It’s no longer a Singleton. Maybe it’s a Zeroton, or a Noneton.

Now this implementation, like the previous ones, still has the flaw that its values are actually integers, and nothing keeps us from, say, adding 1 to Saturday and getting Octidi. But it will do for most applications. For a discussion of techniques for value restriction and type safety, see Implementing Enumerated Types in Java.

  • http://www.darronschall.com darron

    The original post you referenced from me was a long time ago, and better ways have been discovered since then. Check out Jason’s post here, and the discussion in the comments.

    http://blog.jasonnussbaum.com/?p=48

  • alan

    Thanks, Darron, that’s indeed better!

  • http://blog.jasonnussbaum.com Jason Nussbaum

    And way late…thanks, Darron/Alan.

    J.

blog comments powered by Disqus