I just ran into this idea when porting dcollections to D2.

I have the following interface:

interface Addable(V)
{
  Addable add(V v);
  Addable add(V v, out bool wasAdded);
}

In all cases, I have implemented add(V) as:

MyContainerType add(V v)
{
   bool ignored;
   return add(v, ignored);
}

I would like to make add(V) a final function in the interface, except for one problem -- covariance. The reason I return 'this' when adding is so you can chain together many operations. Because of covariance, this works awesome because you always get back the type you are using.

But if I make add(V v) a final interface function, then MyContainerType cannot override it, and things like this won't work:

myContainerType.add(5).myContainerTypeSpecialFunction();

Plus, even if you *could* override it (a la Andrei's overridable interface methods), the implementation would be identical, so that's a lot of mindless coding.

It would be nice to be able to flag a final interface function (or any function for that matter) to indicate that it returns 'this', meaning it should be covariant automatically without repeating the implementation. I don't know if there's a way to do this so the compiler doesn't have to actually generate another function to implement it in the derived class, but even that would be OK. Even helping with the mindless recoding of the same simple function would be great. It can also be another point of documentation (I *know* this function returns the owner object because the signature says so).

A proposed syntax:

final return this add(V v)
{
  bool ignored;
  add(v, ignored);
  // no return necessary?
}

There's probably not a huge need for it, but I just thought I'd put the idea out there.

-Steve

Reply via email to