3.2 Type Syntax

 <  Day Day Up  >  

Now that we've had a general introduction to type checking in ActionScript 2.0, let's study the syntax more formally . ActionScript 2.0's compile-time type checking can be applied to:

  • A variable

  • A property

  • A function or method parameter

  • A function or method return value

To enable type checking for any of the preceding items, we declare the item's type using post- colon syntax, as discussed earlier and in the next section. Declaring an item's type tells the compiler what kind of data it should contain. Armed with that knowledge, the compiler can warn us of two possible error conditions:

  • If a value of an incompatible type is stored in a variable, passed as a function parameter, or returned by a function, the compiler generates a type mismatch error.

  • If a nonexistent property or method is accessed through a typed variable, function parameter, or function return value, the compiler generates an error explaining that the property or method cannot be found.

The compiler selectively type checks only items that have their types declared. Unfortunately, Flash MX 2004 does not provide a way to force the ActionScript compiler to report which items have no datatype declared. Hence, type errors can slip through if you're not vigilant about declaring datatypes. (For comparison, in Java, a program will not compile if any datatype declarations are missing.)

3.2.1 Declaring Variable and Property Datatypes

To declare the datatype of a variable or property, use the following syntax:

 var   variableOrPropertyName   :   datatype   ; 

where variableOrPropertyName is the name of the variable or property, and datatype is the type of data that the variable or property can legally contain. For example, the following code creates a variable called currentTime and declares its datatype as Date . It then assigns a new Date instance to the variable, which is legal, because the class of the instance is compatible with the datatype of the variable:

 // Create a variable that can contain only data  // compatible with the   Date   datatype. var currentTime:Date; // Store a   Date   instance in the   currentTime   variable. currentTime = new Date( ); 

We could also reduce the preceding two lines to a single step:

 var currentTime:Date = new Date( ); 

If you mistakenly refer to a nonexistent datatype in a datatype declaration or elsewhere, the compiler will return the following message:

 The class '<NONEXISTENT_TYPE>' could not be loaded. 

Once a variable's datatype is declared, it is fixed until the variable is destroyed . Attempts to assign any value not compatible with the original type cause a type mismatch error at compile time. For example, this code attempts to assign a Number to currentTime , whose datatype was declared as Date :

 var currentTime:Date; currentTime = 10; 

That code yields the following compile-time error:

 Type mismatch in assignment statement: found Number where Date is required. 

Attempts to access any property or method on currentTime that is not defined by the Date class likewise yields an error. For example, this code:

 // Create a typed variable. var currentTime:Date = new Date( ); // Attempt to access the nonexistent   _width   property. currentTime._width = 20; // Attempt to access the nonexistent   sort( )   method. currentTime.sort( ); 

yields the following errors:

 There is no property with the name '_width'. There is no method with the name 'sort'. 

Note that in order to report nonexistent methods and properties, ActionScript 2.0 prevents new properties or methods from being added to individual objects after they have been created (unlike ActionScript 1.0, which allows such additions). For example, in ActionScript 2.0, the following code is illegal, but in ActionScript 1.0, it is allowed:

 var currentTime:Date = new Date( ); currentTime.name = "Day One";  // Illegal in ActionScript 2.0, but                                // legal in ActionScript 1.0. 

As we'll learn in Chapter 4, ActionScript 2.0 provides a special means of creating classes whose instances allow new properties and methods to be added at runtime. However, instances of these classes cannot, by definition, be checked for nonexistent methods and properties. Later in this chapter, under "Bypassing Type Checking on a Per-Use Basis," we'll see that ActionScript 2.0's type checking can also be disabled on a per-object basis.

But remember that type checking is intended to help you write better code more quickly. Don't try to avoid it by, say, changing the datatype of a variable as follows :

 var currentTime:Date; var currentTime:Number; 

In ActionScript 2.0, the preceding code does not change the datatype of currentTime to Number . The second line is simply ignored and later attempts to assign a numeric value to currentTime will generate errors.

However, due to a bug in the ActionScript 2.0 compiler in Flash MX 2004, the following code does change the datatype of currentTime from Date to Number :

 var currentTime:Date; var currentTime:Number = 10;  // Redeclare with assignment. currentTime = 11;             //   currentTime   's datatype is now   Number.   

The preceding code redeclares the datatype of the variable currentTime and also reassigns its value. The reassignment causes the ( buggy ) change in the variable's datatype. Such code is ill advised, as the official behavior will very likely change in the future.

Instead of redeclaring a variable's datatype, you should use two separate variables when you need to store values of two different datatypes. That said, you can safely reuse a loop counter when its datatype is the same across multiple loops in the same script, function, or method. Just remember to omit the keyword var , the colon, and the datatype on the second and subsequent loops. For example:

 // First loop: declare   i   as a   Number   . for (var i:Number = 0; i < 10; i++) {   trace(i); } // Second loop: reuse   i   , but don't include   var   or   :Number   . for (i = 15; i > 0; i--) {   trace(i); } 

In a loop in which a different datatype is required, use a new variable:

 // Use   p   instead of   i   . for (var p:String in someObj) {   // List properties of an object.   trace("Found property: " + p); } 

Naturally, local variables within one function have no relation to local variables within a separate function. So you could have a local variable declared as a number in one function and a different local variable of the same name declared as a string in another function.

3.2.2 Declaring Method Parameter and Return Value Datatypes

The following code shows how to declare the datatype of method or function parameters and return values:

 function   methodName   (   param1Name   :   param1Type   ,   param2Name   :   param2Type   ):   returnType   {   // ... } 

where methodName is the name of the method or function, param1Name and param2Name are the names of the parameters, param1Type and param2Type are the parameters' datatypes, and returnType is the datatype of the function's return value. This example shows a function with two parameters but, naturally, a function declaration may have zero or more parameter:datatype pairs, separated by commas. Functions that return no value should specify a returnType of Void . But note that the Void type is reserved for use only as a function returnType . To declare a variable or parameter with a datatype that can accommodate any value, use the Object type, as described in the later section, "Compatible Types."

The following code creates a function, largerThanTen( ) , that checks whether a numeric value is greater than ten. It requires a single numeric argument and returns a Boolean result (either true or false ):

 function largerThanTen (n:Number):Boolean {   return n > 10; } 

If we pass a nonnumeric value to the function, the compiler issues a type mismatch error, indicating the location of the error in your code by line number. For example, the following code:

 largerThanTen("colin"); 

yields this error (line number omitted):

 Type mismatch. 

If, within the function, we access a nonnumeric property or method on n , the compiler generates an error. For example, the following code:

 function largerThanTen (n:Number):Boolean {   n.charAt(0);   return n > 10; } 

yields this error:

 There is no method with the name 'charAt'. 

Returning anything but a Boolean value from the function also causes a type mismatch error. We'll revisit return-value type mismatch errors with examples when we study methods in the next chapter.

Finally, storing the return value of a function or method in a variable or property of an incompatible type causes a type mismatch error. For example, the following code attempts to store a numeric return value in a String variable:

 function sum (x:Number, y:Number):Number {   return x+y; } var result:String = sum(10, 20); 

In response, the compiler generates the following error:

 Type mismatch in assignment statement: found Number where String is required. 

Refer to the discussion accompanying Examples Example 3-2 and Example 3-3 for ways of addressing this sort of type mismatch error.

Accessing nonexistent methods and properties on a typed return value also causes an error. This attempt to call getYear( ) on a numeric return value:

 sum(10, 20).getYear( ); 

yields this error:

 There is no method with the name 'getYear'. 

Remember, these errors are your best friends . Don't think of them as scolding you or complaining about something that's not your problem. You should thank the compiler for telling you when you've made a mistake, just as you'd thank your neighbor for pointing out that you left your keys in your front door. Every time the compiler generates a datatype- related error, think to yourself, "Wow, I just saved a few minutes or maybe a few hours tracking down that problem myself !"

In an object-oriented Flash application, be sure to provide a datatype for each property, variable, method parameter, and method return value. If you omit the datatype of an item, ActionScript 2.0 performs no type checking on it and cannot warn you about datatype-related errors in your code.

In Chapter 4, we'll study method definition again, in much greater detail.

3.2.3 Why Post-Colon Syntax?

As we've learned in this section, ActionScript 2.0 uses the following, slightly unusual syntax for type declarations:

   variableOrPropertyName   :   datatype   =   value   ; 

By contrast, Java and C++ use:

   datatype     variableName   =   value   ; 

In JavaScript 2.0: Evolving a Language for Evolving Systems , Waldemar Horwat (one of the creators of the ECMAScript 4 specification) explains the reason for this difference at http://www.mozilla.org/js/language/evolvingJS.pdf.

figs/as1note.gif Embarrassingly, this is a decision based purely on a historical standards committee vote ”this seemed like a good idea at one time. There is no technical reason for using [post-colon] syntax, but it's too late to reverse it now ( implementations using this syntax have already shipped), even though most of the people involved with it admit the syntax is a mistake.

 <  Day Day Up  >  


Essential ActionScript 2.0
Essential ActionScript 2.0
ISBN: 0596006527
EAN: 2147483647
Year: 2004
Pages: 177
Authors: Colin Moock

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net