User Guide
Assigning data types to elements 43
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 doesn’t 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 can’t 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 can’t cast to Array because the
Array() conversion
function takes precedence over the cast operator. For more information on data conversion
functions, see the entry for each conversion function in Flash ActionScript Language Reference:
Array(), Boolean(), Number(), Object(), 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 item’s 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.
The following example shows how you can use these operators and the difference between them:
//Create a new instance of LoadVars class
var myLV:LoadVars = new LoadVars();
//instanceof operator specifies instance of what class
if (myLV instanceof LoadVars) {
trace("yes, it's a loadvars instance");
}
//typeof operator does not specify class, only specifies that myLV is an object
var typeResult:String = typeof(myLV);
trace(typeResult);
For more information about these operators, see typeof and instanceof in Flash ActionScript
Language Reference. For more information on testing and debugging, see Chapter 4, “Writing and
Debugging Scripts,” on page 139.