generic factory method

I show you how to create a factory method for a Generic Class.
It's really simple, if you know how it works ;)

let's say you have a generic class Item<T>

class Item<T> 
{
    public var value:T;

    public static function create <T> ():Item<T> // factory method
    {
        return new Item<T>();
    }

    private function new () {}  // private constructor

}
// test it
class Main 
{
    public static function main () 
    {
        // this works because of type-inference, the 
        // compiler knows that the return type must be of type Item<Int>
        var myItem:Item<Int> = Item.create(); 
        myItem.value = 10; // works
        trace(myItem.value); // 10
        
        // complex type    example
        var myItem2:Item<Array<Int>> = Item.create();
        myItem2.value = [1, 2, 3]; // works too
        trace(myItem2.value); // [1,2,3]
    }
}

that's it!

version #7107, modified 2009-10-19 19:12:15 by hhoelzer