Our Blog

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.

Nahuel Foronda

Nahuel Foronda

4 Comments

  1. Cesar Tardaguila
    I've found som strange issues when casting too.

    There was one strange behaviour when casting to array, that I'm not able to reproduce right now, but I'll try to remember.

    Anyway, some times, you can loose a lot of time because of these little things, so thanks for sharing.
  2. Nahuel

    Hi Cesar
    You are totally right, I spent like an hour trying to debug an application and trying to understand this behaviour.
  3. Thomas
    hi,
    this post is a little dated, but the problem still exists. i think i've found the reason, unfortunately no solution (in the case of array):

    http://www.blog.lessrain.com/?p=203
  4. I just ran into the array casting problem and found this article. Since I couldn't find a solution, anywhere, here's what I came up with:

    var tmp_obj = c.getItem(); // Get item, and auto cast to an un-typed variable
    some_arr = tmp_obj; // Assign to array object