[fpc-devel] suggestion: virtual method co-variance
Sven Barth
pascaldragon at googlemail.com
Wed Oct 15 07:49:15 CEST 2014
On 15.10.2014 04:21, Hans-Peter Diettrich wrote:
> Sven Barth schrieb:
>
>> At least at first sight there don't seem to be any real (technical)
>> reasons to not covariance for return values. Parameters would be a
>> different topic though...
>>
>> Just so I get the idea right:
>>
>> === code begin ===
>>
>> type
>> TBar = class
>> function Test: TObject; virtual;
>> end;
>>
>> TFooBar = class(TBar)
>> function Test: TStrings; override;
>> end;
>>
>> //...
>
> I just wonder about the purpose and use of such refinement. Should the
> compiler relate on an more specific return type, based on the *static*
> type of an object reference? I'd use different names for specialized
> methods/properties instead.
The compiler should take into account the type of the variable on which
the method is called. See the example code which you have snipped away. ;)
And btw: the compiler even already does that! :)
> OTOH it would be nice to have specialized lists without much coding,
> i.e. without writing getters (and setters) which only do typecasts of
> their results. Something like
>
> type
> TBar = class
> property Test: TObject ...; virtual;
> end;
>
> TFooBar = class(TBar)
> property Test: TStrings; override;
> end;
>
> Please note that this kind of override should not require to override
> the getters/setters, it only would enforce (static) type checks/casts,
> as doable at compile time.
But here the compiler can't guarantee that the Getter behind the
property is really a TStrings instead of a TObject. And for the setter
we would have the same problem as for methods: if I call the property
using a TBar variable and pass something else than a TStrings than the
inherited Setter will be called and then (to use the example of a list)
a foreign object will reside in the list.
Regards,
Sven
More information about the fpc-devel
mailing list