Search code examples
delphigenericsdelphi-xe7

How to use generics as a replacement for a bunch of overloaded methods working with different types?


I have a bunch of overloaded methods, all of them get an array of some type as a parameter and return a random value from that array:

function GetRandomValueFromArray(Arr: array of String): String; overload;
begin
     Result := Arr[Low(Arr) + Random(High(Arr) + 1)];
end;

function GetRandomValueFromArray(Arr: array of Integer): Integer; overload;
begin
     Result := Arr[Low(Arr) + Random(High(Arr) + 1)];
end;

etc.

How can I use generics to create a single method for array of any type? Something like this (does not compile in Delphi XE7):

function GetRandomValueFromArray(Arr: TArray<T>): <T>;

Appreciate any opinion as I read most of questions about generics and it's still not clear for me is it possible at all or not?


Solution

  • To use generic function, you have to convert it into method of class (weird limitation, in my humble opinion). Note that class function does not require to create an instance of TDummy

    TDummy = class
      class function GetRandomValueFromArray<T>(const Arr: TArray<T>): T;
    end;
    
    class function TDummy.GetRandomValueFromArray<T>(const Arr: TArray<T>): T;
    begin
      Result := Arr[Low(Arr) + Random(High(Arr) + 1)];
    end;
    
    intValue := TDummy.GetRandomValueFromArray<Integer>([1,3,5]);