Dynamic Casting and * in ActionScript 3
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:
- var nNum:uint = 5;
- 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:
- public function helloUntypedVariable(myVar:*):void
- trace("hello " + String(myVar));
If you have an untyped variable you can determine which type of variable it is at runtime using the is operator:
- public function customTypeOf(dataObject:*):String
- if (dataObject is uint)
- return "uint";
- if (dataObject is String)
- return "String";
- var n:uint = 5;
- var s:String = "Hello World";
- trace( customTypeOf(n) ); // traces "uint"
- 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:
- var n:int = 5;
- trace(n is uint); // traces "true"
- trace(n is int); // traces "true"
- trace(n is Number); // traces "true"
- 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.