Plain old covariance and contravariance

Hasan Aljudy hasan.aljudy at gmail.com
Tue Oct 17 05:39:46 PDT 2006



Reiner Pope wrote:
> I did some searching for variance here, and I couldn't find much 
> discussion of it. My question (I think) is quite simple: why is 
> covariance supported but not contravariance?
> 
> interface Foo
> {
>   Foo get();
>   void set(Bar x);
> }
> 
> interface Baz : Foo {}
> 
> class Bar : Foo
> {
>   Bar get() {} // Fine
>   void set(Foo x) {} // Error, doesn't implement Foo.set
> }
> 
> For some reason, Bar.set isn't taken to be the implementation of 
> Foo.set, even though it will work for any parameters that Foo.set does.
> 
> What am I missing?
> 
> Cheers,
> 
> Reiner

I think that's because Bar.set can also accept invalid parameters, such 
as X, where X extends Foo.

class X : Foo
{
  ...
}



More information about the Digitalmars-d mailing list