Object oriented programming and interfaces

Steven Schveighoffer schveiguy at yahoo.com
Tue Dec 5 17:19:18 UTC 2017


On 12/4/17 3:43 PM, Dirk wrote:
> Hi!
> 
> I defined an interface:
> 
> interface Medoid {
>      float distance( Medoid other );
>      uint id() const @property;
> }
> 
> and a class implementing that interface:
> 
> class Item : Medoid {
>      float distance( Item i ) {...}
>      uint id() const @property {...}
> }
> 
> The compiler says:
> Error: class Item interface function 'float distance(Medoid other)' is 
> not implemented
> 
> Is there a way to implement the Item.distance() member function taking 
> any object whose class is Item?

You are thinking about covariance and contravariance.

In D, only the return value can work with covariance:

interface Medoid {
    Medoid getIt();
}

class Item : Medoid {
    Item getIt() { return this; }
}

D does not support contravariance on parameters. And in any case you 
have it backwards. A derived override could take a base type, but not a 
more specific type, for the reasons Adam outlined.

-Steve


More information about the Digitalmars-d-learn mailing list