When are associative arrays meant to throw a RangeError?

Ben Davis entheh at cantab.net
Sat Feb 18 16:13:12 PST 2012

On 18/02/2012 23:33, Andrej Mitrovic wrote:
> Well it's probably too late to change this behavior. Both the sample
> on the hash page and TDPL itself shows the usage of that trick.

That's fine - but let's document it :)

A few things seem to be missing:

- You get a RangeError for reading a nonexistent key;

- However, you can safely write a[k]=a[k]+1 or a[k]++, because if a[k] 
doesn't exist, then a[k]=b sets a[k] to the default value first before 
evaluating b. (This is a special case for assoc array assignments, not 
for other assignments.)

- .init property for assoc arrays returns null.

- For dynamic arrays and assoc arrays, 'null' is an empty array, so you 
don't have to worry about null crashes like with objects.

Here are the tests I did to confirm the above:

//prints "[]"

int[string] assoc=null;
//prints 0

//breaks the compiler for me :P but not an important use case

int[] dyn=null;
//prints 0

> Btw, if you really want Type.init if the key doesn't exist you can use
> the get method:
> Chunk[] tempVar = chunks.get("CCCC", null) ~ new Chunk();

Yes, good to know! I see it's in the docs too. Thanks :)

More information about the Digitalmars-d mailing list