Search code examples
haxe

Using an array as a parameter in Haxe


I have a function that takes an array as a parameter, and it keeps returning the following error message:

Test.hx:34: characters 23-24 : Array<Int> should be { length : Void -> Int }
Test.hx:34: characters 23-24 : Invalid type for field length :
Test.hx:34: characters 23-24 : Int should be Void -> Int
Test.hx:34: characters 23-24 : For function argument 'array'

This is the code that produced the error message:

class Test{
    static function main() {
        var a = new Array();
        a  = [1,2,3,4];
        enlarge1DArray(a); //why won't it work when I try to invoke this function?
    }

    static function enlarge1DArray(array){
        var i = 0;
        while(i < array.length()){
            i++;
            trace("i is " + i);
        }
    }
}

Solution

  • The length you are trying to access is a property, not a method. See the Array API Documentation.

    Change the while line from this:

    while(i < array.length())
    

    to this:

    while(i < array.length)
    

    Detailed Answer:

    The error you're getting is due to Haxe getting confused as it's guessing at the types. Basically, because you had were treating length as a method, it was assuming that the array parameter in the enlarge1DArray had to be some kind of object that had a method called length, with the type signature "Void->Int".

    In short, because you were asking for a method, it was expecting the parameter "array" to have:

    { length : Void -> Int }
    

    when an Array actually has:

    { length : Int }
    

    So the compiler got confused and said you had your typing wrong. You can read more about this on the Haxe wiki page for Type Inference. In future you can explicitly state what the types of each function parameter are, and then Haxe will give you more useful error messages.