This discussion is necessary in order to continue with our network programming lessons.

Casting (converting one variable type to another) in ActionScript 3 is very easy. The following code casts a uint as a String:

ActionScript
< view plain text >
  1. var  nNum:uint = 5;
  2. var  sNum:String = String(nNum);

But what if you don’t know what the variable should be cast as? For example, let’s say you have a client-server application. The server sends you an XML packet that contains the data for a variable and it tells you what the type of the variable should be with a written String expression. Your goal is to store this data in a variable of the proper type.

First, you have to know about the * (Special Type) operator. This can be used to create a variable that is “untyped.” For example, the following function can take any type of variable as a parameter:

ActionScript
< view plain text >
  1. public function helloUntypedVariable(myVar:*):void
  2. {
  3.     trace("hello " + String(myVar));
  4. }

If you have an untyped variable you can determine which type of variable it is at runtime using the is operator:

ActionScript
< view plain text >
  1. public function customTypeOf(dataObject:*):String
  2. {
  3.     if (dataObject is uint)
  4.         return "uint";
  5.     if (dataObject is String)
  6.         return "String";
  7. }
  8.  
  9. var n:uint = 5;
  10. var s:String = "Hello World";
  11.  
  12. trace( customTypeOf(n) ); // traces "uint"
  13. trace( customTypeOf(s) ); // traces "String"

It’s important to note that the “is” operator returns true for anything and everything that the variable in question is qualified to be. For example, the following code all returns true:

ActionScript
< view plain text >
  1. var n:int = 5;
  2. trace(n is uint);   // traces "true"
  3. trace(n is int);    // traces "true"
  4. trace(n is Number); // traces "true"
  5. trace(n is String); // traces "true"

Even though n is of type “int”, it even returns true in the statement “n is uint” because the value is positive and therefore qualifies to be a uint.

Now we know enough to create our “CustomCaster” utility class. This static class has two purposes: to determine the most restrictive type of a variable (CustomCaster.customTypeOf) and to cast a variable as some other data type that can be specified at runtime (CustomCaster.customCast):

Download the latest version here.

This work, unless otherwise expressly stated, is licensed under a Creative Commons Attribution-Noncommercial 3.0 United States License.