Friday, September 12, 2008

Typed container in AS3

In ActionScript3, how can you define and enforce type for an
Array. Something like the following:
var a:MyArray = new MyArray(NetConnection, 2);
a[0] = new NetConnection(); // should work
a[1] = "some string"; // should fail with exception.

1 comment:

Kundan said...

You can use a Proxy object for this. See this on how to use Proxy.

dynamic public class MyArray extends Proxy
{
private var _type:Class;
private var _item:Array;
public MyArray(type:Class,num:uint=0)
{
_type = type;
_item = new Array(num);
}
...
override flash_proxy function setProperty(name:*, value:*):void {
if (!(value is _type))
throw new Error("value is not " + _type);
_item[name] = value;
}
}