Alex Rivera | Logout

ActionScript: Is there ever a good reason to use 'as' casting?

Asked 2009-06-15T14:38:11.263
17

From what I understand of ActionScript, there are two kinds of casts:

var bar0:Bar = someObj as Bar;  // "as" casting
var bar1:Bar = Bar(someObj); // "class name" casting (for want of a better name)

Also, and please correct me if I'm wrong here, as casting will either return an instance of the class or null, while "class name" casting will either return an instance of the class or raise an exception if the cast is impossible – other than this, they are identical.

Given this, though, as casting seems to be a massive violation of the fail-fast-fail-early principle... And I'm having trouble imagining a situation where it would be preferable to use an as cast rather than a class name cast (with, possibly, an instanceof thrown in there).

So, my question is: under what circumstances would it be preferable to use as casting?

Edit
Report

1 Answer

11

You need to use as to cast in two scenarios: casting to a Date, and casting to an Array.

For dates, a call to Date(xxx) behaves the same as new Date().toString().

For arrays, a call to Array(xxx) will create an Array with one element: xxx.

The Class() casting method has been shown to be faster than as casting, so it may be preferable to as when efficiency matters (and when not working with Dates and Arrays).

import flash.utils.*;

var d = Date( 1 );

trace( "'" + d, "'is type of: ",getQualifiedClassName( d ) );

var a:Array = Array( d );

trace( "'" + a, "' is type of: ", getQualifiedClassName( a ) );

    //OUTPUT
        //'Mon Jun 15 12:12:14 GMT-0400 2009 'is type of:  String
        //'Mon Jun 15 12:12:14 GMT-0400 2009 ' is type of:  Array

    //COMPILER ERRORS/WARNINGS:
        //Warning: 3575: Date(x) behaves the same as new Date().toString(). 
        //To cast a value to type Date use "x as Date" instead of Date(x).
        //Warning: 1112: Array(x) behaves the same as new Array(x).
        //To cast a value to type Array use the expression x as Array instead of Array(x).

`

answered 2009-06-15T16:17:52.910

Your Answer