Since I switch between languages a fair amount I find it hard to keep track of each’s idiosyncrasies in common constructs. Presently I shall briefly note AS3′s implementation of Dictionaries, Arrays and Objects and differences therein:
Object
- Maps String keys to Object values.
- Features the convenience constructor {}
- Access members with brackets or dots. Dots convert the argument into a String literal. For example:
var bobby_b:String = "cello";
var arrgh:Array = [];
arrgh[bobby_b] = "uhn"; //equivalent to arrgh["cello"] = "uhn";
arrgh.bobby_b = "yeah"; //equivalent to arrgh["bobby_b"] = "yeah";//post condition:
arrgh["cello"] => "uhn"
arrgh["bobby_b"] => "yeah"
- Can lift (press) 10 tons
Array
- Are actually associative arrays, as expected, so no speed benefit there.
- Equivalent to Object. One might go so far as to say they are identical, if one was confident in this, but sadly one is not.
- Feature the convenience constructor []
- Probably semantically advantageous over Objects where strict lists will be used.
Dictionary
- Maps Object keys to Object values
- Can use Array syntax for addressing
- Has no convenience constructor
- Must be imported from flash.utils
- for…in loops don’t understand Object keys – it always expects Strings – so one must cast the key to the desired type to avoid compiler errors:
for (var key in new_edition){
var member:Musician = key;
// proceed with your life
}
NOT:
for (var key:Musician in new_edition) { ... } //compiler error "Implicit coercion of a value of type String to an unrelated type Musician"
OR:
for (var key:Object in new_edition) { ... } //compiler error "implicit coercion of etc"
BUT MAYBE:
for (var key:* in new_edition){ ...}
AND ALSO:
for (var key in new_edition){
key = key as Musician;
// do whatever
}
AND ALSO MAYBE:
for (var key in new_edition){
//and just don't even bother with the cast, they'll figure it out
}
That last one is nice for typing, but not nice for typing, if you take my meaning. Kinda defeats the purpose of the kinda-type system they so painstakingly (?) crafted. Recommendation: use the first form with an explicit cast and an extra variable so you get the benefit of the compiler.
- Cannot by typed correctly by me on the first try. I always write “Dicionary”. Can’t stop.