1 Reply Latest reply on Dec 23, 2006 10:58 AM by peterent

    Using the "as" operator vs casting?

    ntsiii Level 3
      I've recently been reading the docs regarding data types in AS3 and am still not clear on a few things. If anyone has blogged on this, please point me there.

      One problem is that "casting" syntax is the same as top-level function syntax. Compare String(objString) to XML(event.result). The latter is a top-level function, but the former is a "cast". Or is it?

      An option to the String cast is objString.toString(). What is the difference? I am not so much interested in the underlying details of the language, as in understanding when to use which.

      The same question exists for the top-level function XML(event.result), which can be done with the "as" operator: event.result as XML. When to use which? Are there performance issues? The "as operator" documentation is unsatisfying.

      Any discussion of this will be appreciated.

      Tracy
        • 1. Re: Using the "as" operator vs casting?
          peterent Level 2
          ActionScript 3.0 has the as operator because it circumvents a deficiency with the cast operation () in ActionScript. Consider this:

          var a:Object = new Array(1,2,3,4);
          var b:Array = Array(a);

          What is b? It is an Array of 1 element: [ [1,2,3,4] ];

          The as operator takes care of this:

          var b:Array = a as Array;

          The actual difference in the operators is that if the variable being cast is not of the proper type, the as operator returns null while the () operator throws an exception:

          var j:Number = Number(a); // exception!
          var k:Number = a as Number; // NaN in this case, but null normally

          The feeling here at Adobe is to use the as operator since it is not ambiguous and just check for null. If you prefer to catch exceptions and know when X(y) is a cast vs a conversion, then use that. More of a preference but at times only as will do what you need.