do D support something like C# 4.0 co/contra-variance?

sighoya sighoya at gmail.com
Sun Mar 10 15:12:14 UTC 2019


On Thursday, 2 September 2010 at 10:13:21 UTC, dennis wrote:
> http://blog.t-l-k.com/dot-net/2009/c-sharp-4-covariance-and-contravariance


I think the following could be used as a workaround in most of 
the cases. It is not directly covariance, though.

void covarianceLike(T)(SList!T list)
               
if(is(ImplicitConversionTargets!T==AliasSeq!(Base,Object)))
{
     return;
}

SList!SubClass list= SList!Subclass
covarianceLike(list);

But it is still tedious to write out all base classes as 
AliasSeq, maybe there is a better workaround (Adding extends and 
super kws?).


With a "super" keyword, we could also simulate many 
contravariance scenarios.

I think, true covariance and contravariance is only of limited 
use, the abstraction of them doesn't really map to the underlying 
implementation and may never will so.
Even if we would have no problems with them, how would the loan 
of a list [1,2] to a method accepting 
SList!Algebraic(Int,String,Object) look like if the list inside 
changes to [1,2,Object(),3,String(),4].
Should it affect our original list [1,2] at all? Or should all 
integers be projected out of this heterogenoues list resulting to 
list [1,2,3,4] in the caller?

Modelling covariance and contravariance with parametricity seems 
a better and safer fit to me.


More information about the Digitalmars-d mailing list