Reply to comment

Casting to an Array in AS2

This was originally posted on my blog in May 2007.

An old problem that came back to haunt me today.

Essentially, in AS2 this doesn't work:

var a:Array=[1,2,3];  // Create an array
var b:Object=a; // Works fine, Array is a subclass of Object
var c:Array=b; // Throws a compile error - completely expected, 
               // because the compiler doesn't know that b is an Array
var d:Array=Array(b); // Compiles fine, but gives the wrong answer!

d actually ends up holding the value [[1,2,3]]. That's because AS2's casting syntax is indeed MyObject(object-to-cast), but unfortunately Array(someObject) has a meaning of its own (from old ECMAScript/AS1) - create an array using someObject as a member of the array. So Array(1) equals [1], for example.

I can't find a simple syntactical way around it (and nor, it seems, can anyone else, as far as my Google-fu can tell). I've come across it a number of times before and always dodged it; but this time around I decided to try to come up with a sane solution.

Unfortunately the best/shortest answer I could find to trick the compiler was this:

// Instead of this:
var d:Array=Array(b); // wrong!
// do this:
var d:Array={arr:b}.arr; // right!

It hinges on the fact that Object is a dynamic class, so the compiler throws away type-checking on it. We create a new Object, set its member arr to b, then read it back out again (and this is where the compiler ignores the type-checking).

This does mean creation of an object - very briefly - to perform the cast. If anyone can think of a syntax-only way to do it (i.e. no runtime overhead) that's nice and simple, then please let me know...

It's not such an issue in AS3. Although the Array(x) syntax still exists (I assume for backwards compatibility with the ECMAScript spec) the new casting keyword as solves the problem - the line becomes:

var d:Array=b as Array;

Also, if you do use Array(x), happily the compiler is intelligent enough to warn you.

Reply

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <i> <b> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <blockcode> <h1> <h2> <h3> <h4> <h5> <h6>
  • Lines and paragraphs break automatically.
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>. Beside the tag style "<foo>" it is also possible to use "[foo]".

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Copy the characters (respecting upper/lower case) from the image.