Sunday, June 14, 2009

Typecast slip up in with Numbers in As3

I always seem to run into the same problem with Actionscript 3 when typecasting (converting an object from one type to another). It has to do with the use of the as keyword because I've fallen into the habit of doing all typecasting this way - the benefit being that it will fail gracefully and return the default value for the type you're trying to cast to (usually this is a null).

The trickiness comes when I try to typecast something to a number like this:

var testString:String = "77";
trace( testString as Number );
// Traces null

var testNumber:Number = testString as Number;
trace( testNumber );
// Traces 0

This is a problem because this particular syntax will always return a null, which sometimes leads me to spend too much time tracing this down because sometimes I'm writing code that handles null values gracefully. Anyways, the proper way is:

var testString:String = "77";
trace( Number(testString) );
// Traces 77
Because you're actually utilizing conversion functions for Top Level classes like Number, String, Array, which override casting one might do with the Number(object) kind of syntax when using non-top level classes. These can also lead to unexpected results if you aren't careful.

No comments:

Post a Comment