User Guide

Assigning data types to elements 41
Strict data typing
ActionScript 2.0 lets you explicitly declare the object type of a variable when you create it, which
is called strict data typing. Strict data typing offers several benefits at compile time. Because data
type mismatches trigger compiler errors, strict data typing helps you find bugs in your code at
compile time and prevents you from assigning the wrong type of data to an existing variable.
During authoring, strict data typing activates code hinting in the ActionScript editor (but you
should still use instance-name suffixes for visual elements). Although strict data typing is relevant
only at compile time, it can increase performance at runtime by making your scripts run faster.
To assign a specific data type to an item, specify its type using the
var keyword and post-colon
syntax, as shown in the following example:
// strict typing of variable or object
var x:Number = 7;
var birthday:Date = new Date();
// strict typing of parameters
function welcome(firstName:String, age:Number){
}
// strict typing of parameter and return value
function square(x:Number):Number {
var squared:Number = x*x;
return squared;
}
Because you must use the var keyword when strictly typing variable, you cant strictly type a
global variable (see “Scoping and declaring variables” on page 45).
You can declare the data type of objects based on built-in classes (Button, Date, MovieClip, and
so on) and on classes and interfaces that you create. In the following example, if you have a file
named Student.as in which you define the Student class, you can specify that objects you create
are of type Student:
var student:Student = new Student();
You can also specify that objects are of type Function or Void.
Using strict data typing helps ensure that you dont inadvertently assign an incorrect type of value
to an object. Flash checks for typing mismatch errors at compile time. For example, suppose you
type the following code:
// in the Student.as class file
class Student {
var status:Boolean; // property of Student objects
}
// in a script
var studentMaryLago:Student = new Student();
studentMaryLago.status = "enrolled";
When Flash compiles this script, a “Type mismatch” error is generated because the SWF is
expecting a Boolean value.