Plain old covariance and contravariance

Bruno Medeiros brunodomedeiros+spam at com.gmail
Wed Oct 18 08:30:27 PDT 2006


BCS wrote:
> Hasan Aljudy wrote:
>>
>>
>> Reiner Pope wrote:
>>>
>>> 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
>>> }
>>>
>>
>> I think that's because Bar.set can also accept invalid parameters, 
>> such as X, where X extends Foo.
>>
>> class X : Foo
>> {
>>  ...
>> }
> 
> 
> Why would that be a problem?
> 
> Bar.set can only be called from an instance of Foo or Bar. If it is 
> called by way of Foo, then the parameter will be a Bar, or something 
> derived from Bar (all of which are also Foo s) and thus no problem. If 
> it is called by way of Bar, then the parameter will be a Foo (or Foo 
> derived), again, no problem.
> 
> One potential issue is that class references and interfaces might not be 
> treated quite the same (I am currently doing the homework on this one so 
> I may be wrong). 

Yes, that's the reason. An object can be *converted* to an interface and 
vice-versa, but they are not covariant with each other, precisely 
because of that conversion (the pointer changes). It's not just an 
opaque cast (aka paint cast?).
The reason covariant return types work for classes<->interfaces 
nonetheless is because some special workarounds are put in place to 
convert when necessary between function calls/returns.

>However even getting rid of that doesn't work.
> 
> interface I
> {
>     void set(B);    // all B's are A's
> }
> 
> class A{}
> 
> class B:A{}
> 
> class C:I
> {
>         // any B can be used
>     void set(A a){}
> }
> 
> I would expect that the issue has something to do with the overload 
> resolution rules (it might make the rules more complicated).
> 

Hum, but that should work. Maybe it's a bug.

-- 
Bruno Medeiros - MSc in CS/E student
http://www.prowiki.org/wiki4d/wiki.cgi?BrunoMedeiros#D



More information about the Digitalmars-d mailing list