Quicktip #4: Casting and the ‘as’-keyword

Posted by Bart Claessens on February 15, 2009
ActionScript 3, Flash, Flex, QuickTips

Some of you will probably know the ‘as’-keyword. If not, a short explanation:

The ‘as’-keyword is used to cast an object to another one. (Well it’s not exactly ‘casting’, if someone feels like explaining the difference between casting with the ‘as’-keyword or by using the class constructor, please go ahead in the comment below!).

To make it more concrete, here is an example:

bart as Person

Where ‘bart’ is the variable and ‘Person’ the class you want the variable to cast to.

Now, the trouble starts when you want to use this keyword in combination with other operators.
Why? I hear you asking. Well: the ‘as’-keyword has a lower priority than i.e. the concatenation operator (+) in ActionScript.

To show you in an example:

trace("Result: " + bart as Person);   // The output will look like: "null"

Hu? Yes. It actually concatinates “Result: ” and bart first and than casts the whole thing to a Person object.

The fix is easy:

trace("Result: " + (bart as Person));
  • Share/Bookmark

Tags: , ,

3 Comments to Quicktip #4: Casting and the ‘as’-keyword

Jovan
March 19, 2009

Well, casting like this Person(Bart) is syntax back from as2 (which still works in as3), and casting with ‘as’ is something new introduced in as3. Basicly both do the same thing; typecast an object but Person(Bart) throws a TypeError if it cannot cast Bart to the Person type where as just returns null.

Bart Claessens
March 19, 2009

Hi Jovan!

Thanks for the information!

Thaylin
September 22, 2009

Actually, using the “as” keyword is not necessarily the best option really. Take for instance passing data from an event to another event but casting that data as XML:

dispatchEvent(new DataEvent(Event.COMPLETE, false, false, (event.target.data as XML)));

When tracing out the object it appears to be null but using the proper casting syntax of XML(event.target.data) will return you your correct xml data.

Leave a comment

WP_Big_City