Flash casting weirdness
Now that we have strict typing in ActionScript 2.0, the compiler complains whenever we try to assign a value to a variable that doesn't match its expected type. That is easy to see in the following example:
I made a class ( Container ) that holds any kind of data. Since it is very generic, it only knows that it holds an Object.
This class also has a method ( getItem() ) that returns that data. So if we try to assign the return value of getItem() to a reference of a type other than Object, the compiler will complain:
var c:Container = new Container(new Array());<br />
var i:Array = c.getItem();
the compiler will throw an error like this:
Type mismatch in assignment statement:
found Object where Array is required.
var i:Array = c.getItem();
So the solution for this is to cast the returning data to the class that we need. We have two options:
Option 1 var i:Array = Array(c.getItem());<br />
Option 2 var i:Array = (Array)(c.getItem());
Both works very well except when you try to cast to your own classes, not the built-in ones. To show that, I made another class ( Item ) and a test class ( TestCasting ) that shows this behavior:
Option 1 var i:Item = Item(c.getItem());<br />
Option 2 var i:Item = (Item)(c.getItem());
The first option runs without a problem, but the second doesn't. It simply assigns "undefined" to the variable without the compiler complaining. So it's obviously better to avoid the second option. I used to do it that way because it always works in Java, but not in Flash. You never know when these little things will jump on you.
For a better understanding, I put this example in a zip to download.