Container Contravariance was Re: [typing] Type-erasure re generics
Jonathan M Davis
jmdavisProg at gmx.com
Wed Sep 29 17:40:37 PDT 2010
On Wednesday, September 29, 2010 16:19:48 Jesse Phillips wrote:
> Jonathan M Davis Wrote:
> > > Ok, then let us actually test that and show it is valid[1]:
> > >
> > > class A {}
> > > class B:A {}
> > >
> > > void main() {
> > >
> > > A[] a = new B[6];
> > > a[0] = new A();
> > >
> > > }
> > >
> > > 1. http://ideone.com/5sUZt
> > >
> > > I have shown that what I am talking about is valid for Arrays (a
> > > container) but not templates. The issues of actually implementing it
> > > is not related to what I was replying to. I introduced it as a benefit
> > > to forgetting type information in "generics." I was then told "Having
> > > a container of one type should not be castable to a container of
> > > another type." So I am pointing out we need to remove this feature
> > > from arrays right now!
> >
> > In Java, you can't use generics with arrays, so it's not an issue.
> >
> > But if the D code you give here compiles, then that's a bug and needs to
> > be reported.
> >
> > - Jonathan M Davis
>
> Java you will see that it has no issue converting the container, but throws
> an exception if inserting the wrong type:
>
> http://ideone.com/EZRvn
Ah, okay. That's true: the fact that you can't have generic arrays doesn't stop
you from pointing an array reference of one type at another with a derived type.
I would have thought that it would disallow that though. Well, Java is much
bigger on runtime checks than compile-time checks.
> Ok, I see the point:
>
> class A {}
> class B:A { void fly() {} }
>
> void main() {
> B[] b = new B[6];
> A[] a = b;
> a[0] = new A();
>
> b[0].fly();
> }
>
> http://ideone.com/rLiVL
>
> Which is why others were saying you could have B converted to a const
> container of A as this conversion is good for passing a container of B to
> a function that takes a container of A.
Exactly.
More information about the Digitalmars-d
mailing list