I'm trying to write a generic function that accepts matching parameter types.
Delphi does infer the type parameter correctly in the simple case of plain arguments.
eg:
type
TFoo = class
function Pair<T>(e1, e2: T): TList<T>;
end;
calling this with aFoo.Pair(1, 2);
works perfectly fine, but when I change the parameter signature to a generic type
type
TFoo = class
function InsertInto<T>(aList: TList<T>; aVal: T): TList<T>;
end;
and try to call itaFoo.InsertInto(TList<String>.Create, 'bar');
then the compiler complains about it:E2010 Incompatible types: 'Generics.Collections.TList<uTest.TFoo.InsertInto.T>' and 'Generics.Collections.TList<System.String>'
Is there any way I can write this (or a similar) method, so that the client doesnt have to specity the type parameter?aFoo.InsertInto<String>(TList<String>.Create, 'bar');
My guess is that comes from the strongly typed nature of Delphi.uTest.TFoo.InsertInto.T
is equivalent to System.String
but it's actually a different type.
Much like in this example where Int1
and Int2
are not of the same type:
var
Int1: array[1..10] of Integer;
Int2: array[1..10] of Integer;
...
Int1 := Int2; // <== BOOM! E2008 Incompatible types (in XE2)
The actual problem is not with type inference but with the types not being compatible per the strict rules of Pascal/Delphi.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With