Cannot find symbol

Hello.

This works if and only if testArray is declared outside of the class (at the top of the file):

var testArray = new Array<String>[0];
//inside the class inside some function...
if(testArray.length > 0) {
...
}
If testArray is declared inside the class (for example at the line right above the if statement) then I get this error on the if statement line:
vivoactive5: Cannot find symbol ':length' on type '$.Toybox.Lang.Array<$.Toybox.Lang.String>'.
Am I doing something wrong? Do Arrays need to be global for some reason? Thank you.
  • Monkey C arrays don't have a length property, they have a size() method. Try this:

    if (testArray.size() > 0) {
  • Thank you. That worked. However, I am now confused. Because in another file, I have this and it does work:

    var hrHistoricalDataArray = new Array<Number>[0];//this is a global
    if(hrHistoricalDataArray.length > 1024) {
    ...//this works without any errors.
    }
  • No worries!

    Because in another file, I have this and it does work:

    var hrHistoricalDataArray = new Array<Number>[0];//this is a global
    if(hrHistoricalDataArray.length > 1024) {
    ...//this works without any errors.
    }

    By “works” do you mean that that it simply compiles or that it also works at runtime? I would expect it to crash at runtime.

    The reason you are getting a compile error in one case and not the other is because the typechecker is able infer the type of local variables, and it knows that Lang.Array does not have a length member. In the case of global variables and member variables, the compiler does not know the type with certainty if it hasn’t been declared, as there’s nothing preventing you from reassigning the variable to a value with a different type.

    If you change your global declaration to include an explicit type declaration as follows, you should get the same compile error:

    var hrHistoricalDataArray as Array<Number> = new Array<Number>[0];

  • Thank you very much for the explanation. As usual, your help on this forum is invaluable.