Haxe: how to declare "static" methods in an interface?

This question was asked (and probably answered) in the old Haxe forums on chatting ... but it looks like the whole forum system is no longer functional. So I am asking here:

In Haxe, I need to declare an "interface" to a class that includes a static function "instance ()". But when I do this:

You can't declare static fields in interfaces

So I remove the word "static" from public function instance() [...]

and I get this:

Field instance needed by [...] is missing.

Apparently "Catch-22". But obviously there must be some simple solution. What is it?

+3


source to share


2 answers


As you said, the language does not allow static fields on interfaces. The choice is deliberate. Another thing that doesn't exist is inheriting static fields.

There are several ways to structure your code to avoid this kind of use, which in my opinion does not give you many advantages. A factory pattern or DI approach (I suggest the minject library ) seems to be the most obvious.

Given the comment below, go for the typedef

interface instead:



typedef GetInstance = Void -> Void;

      

You can pass this typedef in much the same way as an interface, with the advantage that you can use both static and instance methods to satisfy this signature.

+5


source


Check out the Singleton library . Any class that implements Singleton will automatically declare a static "instance" variable and a corresponding getter function.



Note. At the time of this writing, the Haxelib version (1.0.0) is out of date. Download the Git version.

0


source







All Articles