Paul Robertson's words, punctuated

Thoughts on development, user-centered design, code, etc. by Paul Robertson

Strongly typed arrays -- coming to ActionScript near you

I’ve been wanting to have strongly typed arrays in ActionScript for a long time. I was pretty excited when I read that it’s part of the EcmaScript 4th edition specification (in the form of the Vector class), and much more excited when I heard that the Vector class is being included in Flash Player “Astro” (as announced at 360 Flex Atlanta by Matt Chotin).

Since the majority of the time when someone’s using an Array in ActionScript, they really want all the elements to be the same type anyway, this is a really great addition and I think it will be used heavily. The Vector class allows (requires) you to specify the type it will contain at compile time – both for variable declarations and when creating instances. In both cases the syntax you use is a “type parameter” suffix .<T>:

var names:Vector.<String> = new Vector.<String>();

The type parameter syntax is part of a separate EcmaScript 4th edition proposal. Sadly they couldn’t make the syntax identical to that for generics in C# (and I believe Java does it the same way), which is almost the same but without the initial . (period). (For an interesting read, take a look at the history of the various options the committee members considered for representing type parameters.)

Anyway, because you specify the type at compile time, the idea is that the compiler can do the type checking for you for adding and getting elements from a Vector instance. In addition, since using Array (and the runtime type checking and type casting that array access involves) has always been a bottleneck in ActionScript performance, I expect that performance improvements can be expected. (Okay, I’ve heard anecdotal reports around the office of much better performance for Vector than for Array.)

Francis Cheng (who’s on the EcmaScript committee) has a couple of nice articles about the Vector class and type parameters, so I won’t bother recreating everything he’s written. Definitely worth a read (like everything he writes).

As an (almost) final note, I should point out that I haven’t seen anything indicating that type parameters will be generally available in “Astro” – just Matt’s announcement about the Vector class specifically.

And finally, on a personal note, I’m excited because I get to do the documentation for the Vector class. It’s always fun getting to write about new features that are personally valuable. And this is one that I’ve definitely been interested in for a while!