Thursday, January 24, 2013

Explicit conversions

The use of explicit conversions, or casting, is helpful when compiling in strict mode because there may be times when you do not want a type mismatch to generate a compile time error. This may be the case when you know that coercion will convert your values correctly at runtime. For example, when working with data received from a form, you may want to rely on coercion to convert certain string values to numeric values. The following code generates a compile time error even though the code would run correctly in standard mode.
var quantityField:String = "3";
var quantity:int = quantityField; // compile time error in strict mode
If you want to continue using strict mode, but would like the string converted to an integer, you can use explicit conversion:
var quantityField:String = "3";
var quantity:int = int(quantityField); // explicit conversion succeeds
In strict mode, the compiler tests for type compatibility with the is operator. If the is operator would return false, the compiler generates an error.
Programming Actionscript 3. Powered by Blogger.