array cast should be supported corrected

Robert Fraser fraserofthenight at gmail.com
Wed Aug 6 17:46:51 PDT 2008


Frank Benoit Wrote:

> interface I{}
> class C : I {}
> 
> C[] carray = getInstance();
> I[] iarray = carray; // compile error
> I[] iarray = cast(I[])carray; // runtime error (1)
> 
> // correct way:
> I[] iarray = new I[carray.length];
> foreach( idx, c; carray ){
> 	iarray[idx] = c; // implicit cast
> }
> 
> I use a template for doing this, but this looks so ugly.
> I[] iarray = arraycast!(I)(carray);
> 
> I think the D compiler should call a runtime method in (1) to do the 
> cast in a loop, instead of doing a simple type change that is not 
> working correctly.


The only way to do this is if the cast performed a copy. Consider:

interface I { }
class A : I { }
class B : I { }

A[] aarray;
I[] iarray = aarray;
iarray ~= new B();
A a = aarray[0]; // you BROKE my TYPE SYSTEM -- this is an instance of B

When upcasting an array you NEED to copy; you cannot alias. And a cast
should never make a copy, since that's unexpected behavior.

In Java, List<A> is not upcastable to List<I>, only to List<? extends I> to
solve this exact problem. This syntax is pretty ugly, though, so I wouldn't
recommend it for D.



More information about the Digitalmars-d mailing list