COMMUNITY

Undocumented overload modifier for java target

I would like to use Haxe to make a cross-platform library, which will be used by different target languages.
While I was investigating the constructor overloading capabilities of Haxe, I stumbled in the overload modifier.
For example I discovered that the following code is valid

class MyClass {
#if java
public overload function new(a: String) {}
public overload function new(a: Int) {}
#end
}

It seems that it works only for the java/jvm target but I am unable to find any documentation about it.
My main concern is that it is an experimental feature that could be removed in a future release.
I would like to know if it has limitations and it is supported by other targets.
Where can I find more information about it?

Overloads like that are supported on java/jvm and C#.
On other targets overloads are also supported, but they have to be extern inline (and thus useless for code used by another language, since extern causes the function to not exist at runtime).
There is a proposal for “full” overload support on all targets: Better Overload Support by TheDrawingCoder-Gamer · Pull Request #93 · HaxeFoundation/haxe-evolution · GitHub

I don’t think it will be removed in future releases. The main reason for supporting it is interoperability with native code, e.g. if you need to implement a native interface with an overloaded method.

As mentioned, there is some support for compile time overloads in Haxe. However “true” overloads are a runtime feature. Even if they were supported in Haxe across targets, then on targets that don’t support them natively, they would either have to be implemented with name mangling (which makes them unusable) or by inspecting argument types at runtime (which makes them expensive).

Especially for constructors I would suggest using static methods instead, e.g.:

class MyClass {
  public function new(a: String) {}
  static public function ofInt(a:Int)
    return new MyClass(Std.string(a));
}

This is portable and while perhaps not idiomatic in every target language, it is still perfectly fine - so long as you can find short and expressive names for the different signatures (not necessarily trivial as they get longer and more complex).

For overloading methods, I’m afraid you’ll have to come up with different names. You can of course use overloading for JVM/CLR, but I suspect users of your API will appreciate that it remains the same should they ever want to use it in another language. But I may be totally wrong about that :smiley: