COMMUNITY

Overriding a method from the variable?

Hello, I’m trying to override the function hello() from the Test2 class and I am running into the error “Cannot rebind this method : please use ‘dynamic’ before method declaration” and I’m not sure where exactly I should place it.

Here is my sample code

class Test {
	static function main() {
		var t = new Test2();
		t.hello = (p) -> {
			trace(p);
		};
		
		t.hello("Foo bar");
	}
}

And this is Test2

class Test2 {
	public function hello(p:String) {}

	public function new() {}
}

You can put this between public and function, so you have

public dynamic function(p:String) {}

But in reality you can put anything before function in any order you like, so you can also do:

dynamic public function(p:String) {}

Here’s the link about dynamic:

1 Like

What about in the case where I’m overriding the method from an instanced variable?

t.hello = (p) -> {
	trace(p);
};

Is this wrong? How should I override the function from an instance?

This is correct, and @tobil4sk is right, you need to add the keyword dynamic to function hello(), here’s a working example:

1 Like

Hej,

You can also do that : Try Haxe !

class Test2 {
	public var hello : String->Void;

	public function new() {}
}
2 Likes

Thank you that clears it up for me! I thought @tobil4sk was saying I had to use full typed function instead of the shorthand version