Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

type inference based on generic argument type (Delphi)

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 it
aFoo.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');

like image 713
astrangeguy Avatar asked Oct 02 '12 15:10

astrangeguy


1 Answers

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.

like image 65
Francesca Avatar answered Oct 16 '22 21:10

Francesca