Associative arrays - non-intuitive 'in' semantics

Ben Davis entheh at
Fri Feb 17 18:47:23 PST 2012

Same example as in the other message:

Chunk[][char[4]] chunks;
chunks["DATA"]~=new Chunk();
if ("DATA" !in chunks) throw new Exception("No DATA chunk");

The exception is thrown. Changing it as follows fixes it:

if (cast(char[4])"DATA" !in chunks) throw new Exception("No DATA chunk");

I can sort of maybe see why this happens, but it is a bit unfortunate. 
As in, my guess is that it's for the same reason HashMap.get() in Java 
accepts Object instead of the key type: because you might want to pass a 
List when the HashMap contains ArrayLists, for example. But the number 
of times I've wanted to do that is far fewer than the number of times 
I've been stung by accidentally passing the wrong object. Should 'in' 
perhaps implicitly cast the LHS to the key type of the RHS?

Maybe best of both worlds is possible: the LHS is implicitly cast if an 
implicit conversion exists, but it's still allowed if not?

Discuss :)

More information about the Digitalmars-d mailing list