Saturday, August 2, 2008

Extending Arrays and Error #1069 with AS3

I don't know what it means and I don't have time to really get into researching it, but sometimes ActionScript seems like a serious OO language and sometimes... it just isn't. One of those times is when you try to extend an Array. Arrays work like this in ActionScript:
var array:Array = new Array();
var b:* = array[235235];

b will evaluate to null. This is not true if you use a class for the Array. For instance:

package
{
public class Blah extends Array
{

}
}

and then you could try the identical thing

var array:Blah = new Blah();
var b:* = array[235235];

but this throws an Error (Error #1069, in fact). Not sure what is up with this nor do I have much time to investigate it.

The solution is easy: use the Facade pattern with Arrays and Dynamic Objects to give them more functionality. Do not extend them. So the Blah class, redone, would read:

package
{
public class Blah
{
private var blah:Array = new Array();
}
}

and then you could add accessors as you see fit.

If you check out the incredible Collection classes at http://www.polygonal.de, you'll see that he never extends Array. He just implements Collection, which is an interface and so is completely fine.

2 comments:

alecmce said...

If you want to extend the Array class, because it is dynamic you must also set your class as dynamic, or you could use Proxy I imagine.

Daniel Rosenstark said...

Thanks Alecmce, I never thought of that. I'll have to give it a try. Althouh Proxies are nice, extension is just the "right thing" in some cases.