Compile time type checking is often favored in larger projects because as the size of a project grows, data type flexibility usually becomes less important than catching type errors as early as possible. This is why, by default, the ActionScript compiler in FlexBuilder 2.0 is set to run in strict mode. You can disable strict mode in FlexBuilder 2.0 through the ActionScript compiler settings in the Project Properties dialog box. In order to provide compile time type checking, the compiler needs to know the data type information for the variables or expressions in your code. To explicitly declare a data type for a variable, add the colon operator (“:”) followed by the data type as a suffix to the variable name. To associate a data type with a parameter, you use the colon operator (“:”) followed by the data type. For example, the following code adds data type information to the xParam parameter, and declares a variable myParam with an explicit data type:
function runtimeTest(xParam:String) {
trace(xParam);
}
var myParam:String = “hello”;
runtimeTest(myParam);
In strict mode, the ActionScript compiler reports type mismatches as compiler errors. For example, the following code declares a function parameter xParam, of type Object, but later attempts to assign values of type String and Number to that parameter. This produces a compiler error in strict mode.
function dynamicTest(xParam:Object) {
if (xParam is String) {
var myStr:String = xParam; // Compiler error in strict mode
trace("String: " + myStr);
}
else if (xParam is Number) {
var myNum:Number = xParam; // Compiler error in strict mode
trace("Number: " + myNum);
}
}
Even in strict mode, however, you can selectively opt of out compile time type checking by leaving the right-hand side of an assignment statement untyped. You can mark a variable or expression as untyped by either omitting a type annotation, or using the special asterisk (*) type annotation. For example, if the xParam parameter in the previous example is modified so that it no longer has a type annotation, the code will compile in strict mode:
function dynamicTest(xParam) {
if (xParam is String) {
var myStr:String = xParam;
trace("String: " + myStr);
}
else if (xParam is Number) {
var myNum:Number = xParam;
trace("Number: " + myNum);
}
}
dynamicTest(100)
dynamicTest("one hundred");