Self type

Cormac Flanagan cormac at soe.ucsc.edu
Tue Aug 14 09:53:26 PDT 2007



Eylon Stroh wrote:
>>From the proposal:
> "The return type T2 is ok, even if the function returns a T1 instead...
> covariant occurrences of Self (eg in the result type) are replaced by
> T2"
> 
> Please correct me if I'm wrong, but it seems to me that return types can
> also be placed in contexts where covariance is not guaranteed.  In the
> following (admittedly contrived) code snippet, the type of y.f cannot be
> function(this:T2):T2, or even function(this:*):T2 (where * denotes
> run-time type checking).  As far as I can tell, it has to be
> function(this:*):*.
> 
> type T1 = { w:int, f:function(this:Self):Self };
> var x:T1 = { w:5, f:function(this:T1):T1
> 	{
> 		var result:T1;
> 		if(this.w < 1)
> 		{
> 			result = { w:1, f:this.f }:T1;
> 		}
> 		else
> 		{
> 			result = { w:this.w-1, f:this.f }:T1;
> 			// this requires f to return T1
> 			result = this.f(result);
> 			result.w *= this.w;
> 		}
> 		return result;
> 	}
> }:T1;
> 
> type T2 = { f:function(this:Self):Self };
> var y:T2 = x;
> 
> Have I missed something that allows for stronger typing of y.f?

As far as I can see, we can give y.f the type

   function(this:*):T2

since T1 is a subtype of T2.

- Cormac



More information about the Es4-discuss mailing list