Alex Rivera | Logout

Javascript array : why is this not valid?

Asked 2011-04-23T18:07:35.247
32

I have the following working code :

var routes = [];

Eclipse validator for javascript prints the following warning :

Type mismatch: cannot convert from any[] to any

What is wrong with my empty array ?

Edit : the warning disappeared later. Apparently Eclipse was wrong and the question needs to be closed. Sorry about that.

Edit
Report

1 Answer

4

As what I observed in my testing so far, the problem occurs when you define a local variable in a function which body following a return keyword. This scenario can be shown in the following example (assuming the code is in a top level JavaScript file, means not inside any module/function so the first a is defined in global scope):

var a=[]; //Global variable assignment, no warnings

function f1(){ //global function
    var a=[]; //level 1 local variable, no warnings
    return a;
}

function f2(){ //local functions and member functions
    var f = function(){
        var a=[]; // no warinings
        return a;
    };
    this.f = function(){
        var a=[]; //no warnings
        return a;
    };
    return f; //returning a defined funciton is OK
}

function f3(){ //returning a function
    return function(){
        var a=[]; //warning: Type mismatch: cannot convert from any[] to any
        return a;
    };
}

So the workaround is simple: change f3 to

function f3(){ //returning a defined function
    var f = function(){
        var a=[]; //warning is gone!
        return a;
    };
    return f;
}
answered 2012-11-24T11:41:45.217

Your Answer