Use Interface to pass Class to function

There’s a workaround for that:

public static function openWindow(?cls:Class<BasicWindow>, ?inst:BasicWindow):Void {
    if(cls != null) {
        inst = Type.createInstance(cls, []);
    }
    
    inst.init();
}

Because the parameters are optional, you can either call openWindow(FancyWindow) or openWindow(new FancyWindow()). In the first case, you’re passing a Class<FancyWindow> object, so it’ll be assigned to cls. In the second case, you’re passing a FancyWindow instance, so it’ll be assigned to inst.

The unused argument will be null. Check which one is null, and use the other. (In the code above, I’m assuming that at least one argument is defined. In fact, think of that as a precondition of the function.)


You can use generics (as described above) if you need this function’s return type to match what it’s given.

static function open<T:(IBasicWindow)>(cls:Class<T>):T {
        var w = Type.createInstance(cls, []);
        return doSomethingTo(w);
}

static function doSomethingTo (instanceOfExtendedBasicWindow:BasicWindow):Void {
        instanceOfExtendedBasicWindow.init();
}

Could you include init in your BasicWindow type, or just do it all in your class constructor? Keep it simple?

hi @singmajesty, yes, to be honest, returning a basicWindow type will work absolutely fine. I was just aware that the casting prevented access to some of the subclass functionality, but in reality the only things that would be ever be accessed would be from the superclass.
I was just trying to gain an understanding about how you’d replicate some of the looser casting available in Flash.

1 Like

Good! That’s the point of having a superclass in the first place.

1 Like