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

For example:

i have two different class objects :

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

and then 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 always asking for the type i tried Dynamic / Any but then it says
load method not found , if i pass only screen then it is getting it as an object but
not the class object.

Type-Safe Way

A good type-safe way of making this happen is to make ScreenA and ScreenB inherit from a common base-class, or implement a common interface:

Base Class

class Screen extends Sprite {
    
    public function new () {
        
        super ();
        
    }
    
    public function load () {
        ...
    }
    
}

You can then override the load function in each screen if they need unique code

Common Interface

interface Screen {
    
    public function load ():Void;
    
}
class ScreenA extends Sprite implements Screen {
    
    public function new () {
        
        super ();
        
    }
    
    public function load ():Void {
        ...
    }
    
}

Dynamic Method

You can also make this dynamic, though it can cause headaches as you begin to use multiple target platforms, and can generally make code more complicated to use. However, it is possible, so here’s how it might look:

Using Dynamic

private function onComp (screen:Dynamic) {
    
    var load = Reflect.field (screen, "load");
    Reflect.callMethod (load, load, []);
    
}

Using Any

private function onComp (screen:Any) {
    
    if (Std.is (screen, ScreenA)) {
        
        var screenA:ScreenA = cast screen;
        screenA.load ();
        
    } else if (Std.is (screen, ScreenB)) {
        
        var screenB:ScreenB = cast screen;
        screenB.load ();
        
    }
    
}
1 Like

You could also pass the method.

Actuate.tween(screenA, 0.6, {alpha: 1} ).onComplete(onComp, [screenA.load]);
private static function onComp(func:Void->Void)
        {
           func();
        }
//OR
private static function onComp(func:haxe.Constraints.Function)
{
   func();
}
1 Like

On that note, you could also use:

Actuate.tween (screenA, 0.6, { alpha: 1 }).onComplete (screenA.load);

Though it may be worth reading the other examples given :slight_smile:

1 Like

Thank you guys i learned allot from these answers . Pretty much well explained and will save allot of time in future :slight_smile:

1 Like