views:

32

answers:

1

if i don't specifically type a variable in my code will it compile as a default datatype? for example, the "for each ... in" function works best without typing the variable:

for each (var element in myArray)
         {
         //process each element
         }

does my element variable have a datatype? if it is typed as Object is it better to actually write element:Object or does it matter?

EDIT

actually, that was a bad example, since the element variable is going to be typed to whatever element is in myArray.

but is that how it works if a variable is untyped? it will simply become what is passed to it?

here's a better example for my question:

var a = "i'm a string"; //does this var becomes a String?

var b = 50.98; //does this var becomes a Number?

var c = 2; //does this var becomes an int?
+3  A: 

for each (var element in myArray)

The element variable doesn't have any data type - it is untyped and thus can hold anything.

And yeah, it is equivalent to writing element:Object or element:*, but it is always advisable to type your variables - this will help you catch some errors before you run the code. The mxmlc compiler will emit a warning if you don't do this, which can be fixed by typing it as e:Object or e:*.


var a = 45.3;  //untyped variable `a`
a = "asd";     //can hold anything

/*
    This is fine:  currently variable `a` contains 
    a String object, which does have a `charAt` function.
*/
trace(a.charAt(1));

a = 23;
/*
    Run time error: currently variable `a` contains 
    a Number, which doesn't have a `charAt` function.
    If you had specified the type of variable `a` when 
    you declared it, this would have been 
    detected at the time of compilation itself.
*/
trace(a.charAt(1)); //run time error


var b:Number = 45.3; 
b = "asd"; //compiler error
trace(a.charAt(1)); //compiler error
Amarghosh
strange. ok, i'll type them, even though i'm using Flash Professional and not Flash Builder, which doesn't give a warning, but i guess it's good to do incase i migrate over to that compiler. also, the actionscript documentation doesn't type the var in the for each ... in loop: http://bit.ly/a2tZc9
TheDarkInI1978
Always type. Not only to catch error, but for performance too. Flash being what it is, it is never a bad idea to look for every possible optimization, specially easy ones like these.
Raveline
always type your variables and eat your vegetables!
grapefrukt