views:

25

answers:

1

Is there any way for me to define implicit or explicit type conversions in ActionScript?

For instance, I want to define a conversion such that Array can cast into MyClass implicitly. If not, an explicit cast would be useful. I know I can always pass it into my constructor, but I am dealing with semantics here, and I am most interested in a conversion solution if it exists.

+1  A: 

Type casting in ActionScript 3

Object(instanceOfOtherObject);

Works based on the valueOf property of the given class (if defined). Therefore, you can define your class MyClass as such:

package {
    public class MyClass {

        private var myArray:Array;

        public function MyClass(inputArray:Array = null) {
            myArray = (inputArray ? inputArray : new Array());
        }

        public function valueOf():Array {
            return myArray;
        }
    }
}

Then you will be able to perform this typecasting:

var mc:myClass = new MyClass();
var arr:Array = Array(myClass);

To my knowledge, the reverse is not an option because the valueOf function of Array does not return an object of type MyClass. There is nothing stopping you from creating a CastableArray that extends and overrides the valueOf function of Array to make it return an instance of MyClass using the constructor I defined above, though you may run into other issues with other fundamental language components that expect an Array to return an Array in its valueOf property (comparison of objects comes to mind).

I have not done any particular testing with this next suggestion, but if MyClass extends from Array and does not define a valueOf function, it may still be possible to do the type conversion depending on the constructor of MyClass and what Flash does in circumstances when valueOf is not defined.

Tegeril
Very informative :) Thanks! I solved my problem by extending the prototype of Array to include `Array.prototype.asMyClass = function ():MyClass {}`. This lets me take any array and call `theArray.AsMyClass()` and it works about as well as I can ask for.
Brian Genisio
That's a clever solution. Glad this was at least of some use, do be aware of the pitfalls about enumeration as defined in this article: http://tobyho.com/Modifying_Core_Types_in_ActionScript_3_Using_the_Prototype_Object
Tegeril