4 Replies Latest reply on Dec 14, 2009 11:52 AM by gdas@nsol

    Type conversion placeholder?

    gdas@nsol

      Hi,

       

      Is it possible to define a variable as one type and later change it to another type?
      What I would like to achieve is a variable that I can cast to different components that all use the IVisualElement class. So the variable exists in a component and later the type is changed inside a funcion. I tried with the "as" operater and the old-fashioned casting with (), but without results. Is there something like a placeholder for the type? Or am I thinking the wrong way?

       

      Here a short example of what may be the code:

       

      private var multiType:IVisualElement;

       

      private function init(type:String):void

      {

           switch(type)

           {

                case "myComponent":

                     multiType = new MyComponent();

                break;

           }

      }

       

      So the idea is that the variable 'multiType' which is of type 'IVisualElement' is changed to type 'MyComponent'.

       

      Thank you for any help.

        • 1. Re: Type conversion placeholder?
          msakrejda Level 4

          To do something like that, you'd need to declare the multiType variable as Object or * and simply forgo type-checking. It's a little bit of a cop-out, but it's not clear what you're trying to do at a higher level--there may or may not be better ways to go about it.

          • 2. Re: Type conversion placeholder?
            gdas@nsol Level 1

            The * type worked fine. I didn't know that that type existed.

            Thank you very much.

            • 3. Re: Type conversion placeholder?
              msakrejda Level 4

              Object should have worked as well, since it's dynamic. Perhaps

              FlexBuilder doesn't like it--it's not terribly smart sometimes. * is

              just like Object, except that it can also hold the value undefined (of

              the type void). I.e., the type hierarchy looks something like

               

                         *

                      /     \

                Object    void (with the one possible value of undefined, like

              Boolean only holds true and false)

                    |

              (all the usual classes)

              • 4. Re: Type conversion placeholder?
                gdas@nsol Level 1

                The type 'Object' results in the following error message:

                 

                1118: Implicit coercion of a value with static type Object to a possibly unrelated type mx.core:IVisualElement.

                 

                I also tried to use IVisualElement as initial type but I did not succeed in casting it to another type (eg: MyComponent) to make all the variables and functions accessible from MyComponent.