Search code examples
haxeopenfl

Passing different class objects into a function and getting it's properties in Haxe?


Passing different class objects into a function and getting it's properties ?

For example:

I have two different class objects :

screenA = new ScreenA();
screenB = new ScreenB();

I pass the objects in the tween:

switch (state)
{

    case States.SCREEN_A:
        {
            Actuate.tween(screenA, 0.6, {alpha: 1} ).ease(Sine.easeIn).autoVisible (true).onComplete(onComp, [screenA]);
        }
    case States.SCREEN_B:
        {
            Actuate.tween(screenB, 0.6, {alpha: 1} ).ease(Sine.easeIn).autoVisible (true).onComplete(onComp, [screenB]);
        }
}

Now i want to access a method of the passed object here, when tween completes.

Tween is passing the object but i am unable to cast it in the function to get the object methods.

private function onComp(screen:?)
{
    screen.load();
}

And compiler is always asking for the type. I have tried Dynamic / Any but then it says "load method not found", If i pass the object without any type arguments in the function then it is getting it as an object but not the class object.


Solution

  • There're a lot of ways you could do this, but one is with a common interface:

    class ScreenA implements OnTweenComplete { ... }
    class ScreenB implements OnTweenComplete { ... }
    
    interface OnTweenComplete {
      public function on_tween_complete();
    }
    

    Then your function is:

    private function onComp(screen:OnTweenComplete)
    {
        screen.on_tween_complete();
    }
    

    Or perhaps, type-check it with Std.is and cast it:

    private function onComp(screen:Dynamic)
    {
        if (Std.is(screen, OnTweenComplete)) {
          (cast screen).on_tween_complete();
        }
    }