0

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?

Joshua
  • 6,643
  • 15
  • 55
  • 76
  • This question has been asked before http://stackoverflow.com/questions/2016201/dynamic-object-initiation-as3 – phwd Jun 09 '10 at 00:13

3 Answers3

1

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
  • 645
  • 3
  • 9
1

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
  • 5,334
  • 4
  • 28
  • 31
-1

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! How bad is dynamic casting?

Community
  • 1
  • 1
Adam Harte
  • 10,369
  • 7
  • 52
  • 85
  • 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 Jun 08 '10 at 23:17
  • If you are casting dynamically, the type will only be known at runtime anyway!?! That is basically the definition of "dynamic casting" – Adam Harte Jun 08 '10 at 23:40