Imagine you have:
var my2dArray:Array = new Array();

my2dArray.push ([1,2,3,4,5]);
my2dArray.push ([6,7,8,9,0]);

And now you want to access and cast an element of myArray to an array:

var firstArray:Array = Array (my2dArray[0]);
trace (firstArray.length);

Right?

Yeah if you’re compiling in MTASC. The Flash IDE doesn’t regard Array(…) as a cast however. It considers the statement as a plz – construct – my – array – and – provide – me – with – hours – of – mind – numbing – debugging.

If you check the code, you’ll see compiling in MTASC prints 5 and compiling in the Flash IDE prints 1.

So how do we fool the compiler to provide a solution that works in both environments ?

var firstArray:Array = [my2dArray[0]][0];

In other words, construct a new array of the element you want to return and return its first element, preventing the compiler from type checking. Nice? No, but it works beautifully and it’s the shortest way there.

It’s okay, you can open your eyes now. So how safe is this? Well I wouldn’t use it across class boundaries for one. And you might wanna add some assert statements, but other than that, buckle up and enjoy the ride :).

If you do want to do it in a more academic way, you can introduce a subclass of Array, for example ArrayCaster:

class ArrayCaster extends Array {

}

and override the constructor where necessary to be fully compatible with the Array class. Once that is done you can do:

var firstArray:Array = ArrayCaster (my2dArray[0]);

Whatever makes you tick :).

image_pdfimage_print
1 reply

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *