Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delphi interface generic function returning TobjectList<T>

Why does this not work? I get a E2511 Type parameter 'T' must be a class type?

type
  IBaseProvider<T> = Interface
    function GetAll: TObjectList<T>;
  end;

type
  TCar = class(TInterfacedPersistent, IBaseProvider<TVehicle>)
    function GetAll: TObjectList<TVehicle>;
  end;

implementation

function TCar.GetAll: TObjectList<TVehicle>;
begin
  // do something with Objectlist
  Result := ObjectList
end;
like image 479
Godfather75 Avatar asked Jun 10 '26 02:06

Godfather75


1 Answers

The parameter T of TObjectList<T> is constrained to be a class.

type
  TObjectList<T: class> = class(TList<T>)
    ....
  end;

You need to declare a constraint that implies this on your type. For example you can declare the same constraint:

type
  IBaseProvider<T: class> = Interface
    function GetAll: TObjectList<T>;
  end;

Or you could declare a stronger constraint, so long as the TObjectList<T> constraint is met. If you don't want to constrain your parameter, then you'd need to use TList<T>.

If you are not familiar with generic constraints, the documentation should fill in the gaps : http://docwiki.embarcadero.com/RADStudio/en/Constraints_in_Generics

like image 84
David Heffernan Avatar answered Jun 11 '26 23:06

David Heffernan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!