Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generics in Object Pascal: types equality

I am trying to learn Object Pascal (maybe for hobby projects), and I found that Object Pascal (FreePascal) supports generics in {$mode objfpc}. They look like C# generics, but it seems as there is a difference. When I tried to declare a variable:

uses Fgl;
...
SomeVariable: TFPSList<string>;

I've got error which said me about unexpected '<' and I removed parameter <string> and it passes compilation. So, seems that list of string's and list of int's would be declared in the same way: Something: TFPSList. But this means that Pascal treats both lists as of the same type, right? In C# and other languages type parameter modifies all type and creates new type. I know that old Pascales used containers of pointers as "generic" solution (TList, etc), but TFPSList is a real generic but in the declaration it looks like simple container of pointers. Does modern Pascal (FreePascal, Delphi) distinguish between these generic types (similar to TFPSList of int's/of string's)? If I have generic list of int's does it mean that I can pass it to the function expecting a list of another type and how/where I should check items type: compile time/runtime? I know about is and as keywords, but what to do if list is empty? How to check the type of container's items?

PS. Excuse me if the question sounds strange or stupid, I never used Pascal before.

like image 237
RandomB Avatar asked Sep 04 '26 13:09

RandomB


1 Answers

in fgl unit TFPSList is not a generic type, its a normal class so you can't specialize it, use TFPGList, your syntax is also wrong, in {$mode objfpc} you need to use specialize keyword for generic, the correct syntax is :

program Project1;

     {$mode objfpc}
    uses Classes,sysutils,fgl;
    type
    SomeType=specialize TFPGList<String>;
     var
       SomeVariable:SomeType;
    begin
      SomeVariable:=SomeType.Create;
      SomeVariable.Add('some string');
    end.

free pascal also generic in Delphi mode {$MODE Delphi} with different syntax, more information here free pascal doc

like image 57
mabudrais Avatar answered Sep 06 '26 23:09

mabudrais



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!