Search code examples
haxeneko

Is it possible to have different signature?


I have the following code :

class Test {
    static function main() {
        trace("Haxe is great!");
        var api:Api = new Api();
        api.doAdd(1,1);
    }
}

class Api {

    public function new(){}

    public function doAdd( x : Int, y : Int ) {
        trace( x + y );
    }

    public function doAdd( x : Int, y : Int , z : Int) {
        trace( x + y + z);
    }
}

Here is a link to a try Haxe code

If I try to compile this code, I get an error : ```Duplicate class field declaration : doAdd````

My question is, is there anyway to have two methods with differents signatures in haxe ?


Solution

  • On the Java and C# targets, the following works:

    @:overload
    public function doAdd(x:Int, y:Int) {
        trace(x + y);
    }
    
    @:overload
    public function doAdd(x:Int, y:Int, z:Int) {
        trace(x + y + z);
    }
    

    On other targets, the syntax for @:overload is a bit different and only works for externs as far as I understand it. There's an example in this thread.