views:

79

answers:

3

Is there a way to cast dynamically in Actionscript? What I want to accomplish is illustrated by the following code:

        var Val:*;
        var S:String=SomeTextEdit.text;
        switch (DesiredTypeTextEdit.text) {
          case 'int':Val=int(S);break; 
          case 'uint':Val=uint(S);break; 
          case 'String':Val=String(S);break; 
          case 'Number':Val=Number(S);break; 
          ...
        }
        SomeDisplayObject[SomePropertyNameTextEdit.text]=Val;

I am looking for something LIKE the following PSEUDOCODE:

SomeDisplayObject[SomePropertyName]=eval(DesiredType)(SomeTextEdit.text);

Yes, I already realize that "eval" is not on the table, nor is that how one would use it.

What's the RIGHT way?

A: 

Not too sure on exactly what you after (your example is a little confusing), but I will try and answer.

You can type-cast a variable only when you create a variable. You can do one of the following to change the type of a variable, but you must create a new variable of the new type.

var foo:Number = 230;
var foo2:int = foo as int;

or

var foo:Number = 230;
var foo2:int = int(foo);

If you use the asterisks (*) as your variable type, then what ever you set the variable to, it will become that type. Try this as a test:

var foo:* = new Sprite();
trace(foo); // Traces: "[object Sprite]"

This is somewhat bad practice, and bad software design. But sometimes you gotta do what you gotta do! http://stackoverflow.com/questions/28080/how-bad-is-dynamic-casting

TandemAdam
This doesn't tell me anything at all about how to cast it dynamically ie: When the destination type of the cast is only known at runtime.
Joshua
If you are casting dynamically, the type will only be known at runtime anyway!?! That is basically the definition of "dynamic casting"
TandemAdam
+1  A: 

You'll have to play the try-catch game, but googling some of these flash.utils would hopefully be a means to your end:

getDefinitionByName(getQualifiedClassName(variable))

You'll probably have to import all of the different 'types' you intend on using into the project somewhere, but this should get you started.

jeremy.mooer
+1  A: 

You might be looking for something like this:

http://benrimbey.wordpress.com/2009/06/20/reflection-based-json-validation-with-vo-structs/

Check the "mapToFlexObjects" function. He's basically reading from text and assigning classes at runtime.

Glenn