User Guide

26 Chapter 1: ActionScript Basics
The syntax for casting is type(item), where you want the compiler to behave as if the data type
of
item is type. Casting is essentially a function call, and the function call returns null if the cast
fails at runtime. If the cast succeeds, the function call returns the original object. However, the
compiler cannot determine whether a cast will fail at runtime and wont generate compile-time
errors in those cases. The following code shows an example:
function bark(myAnimal:Animal) {
var foo:Dog = Dog(myAnimal);
foo.bark();
}
var curAnimal:Animal = new Dog();
bark(curAnimal); // will work
curAnimal = new Cat();
bark(curAnimal); // won't work
In this situation, you asserted to the compiler that foo is a Dog object, and, therefore, the
compiler assumes that
temp.bark(); is a legal statement. However, the compiler doesnt know
that the cast will fail (that is, that you tried to cast a Cat object to an Animal type), so no compile-
time error occurs. If you include a check in your script to make sure that the cast succeeds, you
can find casting errors at runtime.
import Dog;
function bark(myAnimal:Animal) {
var foo:Dog = Dog(myAnimal);
if (foo) {
foo.bark();
}
}
You can cast an expression to an interface. If the expression is an object that implements the
interface or has a base class that implements the interface, the cast succeeds. If not, the cast fails.
Casting to null or undefined returns
undefined.
You cant override primitive data types that have a corresponding global conversion function with
a cast operator of the same name. This is because the global conversion functions have precedence
over the cast operators. For example, you cant cast to Array because the
Array() conversion
function takes precedence over the cast operator. For more information on data conversion
functions, see
Array(), Boolean(), Number(), Object(), and String().
Determining an item’s data type
While testing and debugging your programs, you might discover problems that seem to be related
to the data types of different items. In these cases, you may want to determine an items data type.
You can use either the
typeof operator or the instanceof operator.
Use the
typeof operator to get the data types; typeof does not return information about which
class to which an instance belongs. Use the
instanceof operator to determine if an object is of a
specified data type or not;
instanceof returns a Boolean value.