Casting Vs The “as” operator

Just write a Flex app and try the following in a function

var btn:Button = new Button();

var lst:List = new List();

lst = List (btn);

In short, we are trying to cast a button into a list… What do you expect?? Yes… an RTE (Run Time Error)

It reads

TypeError: Error #1034: Type Coercion failed: cannot convert mx.controls::Button@16ab0479 to mx.controls.List.

There are times in your app development cycle, when you are not sure, if a particular casting is allowed or not. You definitely don’t want to throw an RTE (Run Time Error) to the user either. What you end up doing invariably is using a try…catch block to handle the RTE. A better and cleaner alternative to this is using the as operator

Using the as operator has the following advantages

  • It does the exact same thing as casting does, if you are casting between compatible types
  • It returns a null if the object cannot be casted to a particular type
  • No RTEs 🙂

Once you use the as operator, you can just do a null check to see if the casting is allowed… as below

var btn:Button = new Button;

var lst:List;

lst = btn as List;

if (! lst) {mx.controls.Alert.show(“Sorry you cant cast it this way”); }

But a word of caution. You cannot use the as operator to cast between types in the Top Level classes (to view them , go to the flex language reference). Which means… Say you want to cast a String to a Number, you cannot do,

num = str as Number;

This gives the following error

Implicit coercion of a value of type Number to an unrelated type String

You’ll have to do the age-old way of casting

num = Number(str);

Hope this is useful… at least to beginners 🙂

7 Responses to Casting Vs The “as” operator

  1. IanT says:

    As an aside – the other use for ‘as’ is for casting to Array.

    Because (for historical reasons, I imagine) this:

    var a:Object=[1];
    var b:Array=Array(a);

    results in b being [[1]] (i.e. the Array() operator creates a new array, instead of casting).

    In AS2, this was very difficult to get around. In AS3, just use ‘as’:

    var a:Object=[1];
    var b:Array=a as Array;

  2. raghunathrao says:

    Hey Ian… thanks for the info 🙂

  3. […] Casting Vs The “as” operator Just write a Flex app and try the following in a function var btn:Button = new Button(); var lst:List = new List(); lst […] […]

  4. Kbrom says:

    Just what I needed, thanks for the quick explanation!

  5. Excellent post Ian . I like these posts most of all, practical information that all Flex starters can use. I’ve printed it … Thanks, Zoli

  6. kassel says:

    Hi, excelent point, i try to conver an object to a custom class but takes me a 1009 error, can it do with “as”

Leave a comment