December 05, 2017
On Monday, 4 December 2017 at 20:43:27 UTC, 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?

I think everyone here has missed the reason.

The problem is that a derived type can do more, the interface only allows for two method calls while the class could theoretically do more.

If the compiler allowed the class it would let you access functions and members not available to the interfaces, and the function would still be passed a Medoid.

You could make a cast within your function, but then you're still really not handling the interface but that at least would be clear in the code rather than the compiler hiding it by ignoring the problem.
December 05, 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
1 2
Next ›   Last »