Is it safe to distribute generics in Delphi?

I need to implement a function that returns a TDictionary without specifying exact types. The return value may be TDictionary<string,Integer>, TDictionary<string,string>orTDictionary<string,Boolean>

Can I declare a function with TDictionary as a result parameter:

function GetMap: TDictionary;

and then enter the return value:

type
  TMyMapType: TDictionary<string,Integer>;
var
  MyMap: TMyMapType:
begin
...
  MyMap := GetMap as TMyMapType;
...
end;

Edit: found that there seems to be no way to declare the type of the result parameter "generic" that will be compatible with the type of the three types of dictionaries.

Looks like I need something like

type
      TMyMapType: TDictionary<string, ?>;

which is not (yet?) possible in Object Pascal. In Java, it will be something like this:

static Map<String, Integer>getIntegerMap() {
    Map<String, Integer> result = new TreeMap<String, Integer>() {};
    result.put("foo", Integer.valueOf(42));
    return result;        
}

static Map<String, ?> getMap() {
  return getIntegerMap();
}

public static void main(String[] args) {
    System.out.println(getMap().get("foo"));
}
+3
source share
2 answers

, TDictionary, TDictionary ". . TDictionary<T, U> TEnumerable<TPair<T, U>>, - TObject.

, . , TDictionary<string, TMyObject>, , TDictionary<string, TObject>. , , TMyObject TObject. , .

, , .Add(Self.Name, Self), Self - TForm ( - ), TMyObject. () , , , , , , , .

Generics , , trashing, , Delphi . Delphi Prism , Delphi , ...

+2

GetMap , TDictionary. GetMap T U, TDictionary T U?

:

function GetMap<T, U>: TDictionary<T, U>;

:

var
  MyMap: TMyMapType;
begin
  MyMap := GetMap<string, integer>();
0

Source: https://habr.com/ru/post/1724925/


All Articles