Structs, Arrays, Matrices … [part 2]
Consider a class definition:
TAdvancedDropDownList = class public currPos :Integer; items :Array of String; constructor Create(entryItems :Array of String); end; implementation { TAdvancedDropDownList } constructor TAdvancedDropDownList.Create(entryItems:Array of String); begin items := entryItems; end;
Call this with:
procedure TForm1.FormCreate(Sender: TObject); var items :Array of String; begin items :=['Lorem','ipsum','dolor','sit','amet', 'consetetur','sadipscing','elitr','sed', 'diam nonumy eirmod tempor invidunt', 'ut labore et', 'dolore','magna aliquyam erat', 'sed','diam','voluptua']; TAdvancedDropDown.TAdvancedDropDownList.Create(items); end;
This is not a very god minimum working example. I cut off the unnecessary bits (in context of this post). This will fail. Error Message is :
Error: Incompatible types: got "{Open} Array Of AnsiString" expected "TAdvancedDropDownList.{Dynamic} Array Of AnsiString"
HHHMPH. Turns out, I have to use this trick.
type TStringArray = Array of String; { TAdvancedDropDownList } TAdvancedDropDownList = class public currPos :Integer; items :TStringArray; constructor Create(entryItems :Array of String); end; implementation { TAdvancedDropDownList } constructor TAdvancedDropDownList.Create(entryItems:Array of String); begin items := entryItems; end;
The changes are shown in orange. If I use the type of the argument (violet line in all examples) to the constructor as an Array of String, (it is expecting as such), then the supplied and try to set an Array of String inside the constructor using the said argument, it will fail.
It appears, that the type of the argument to the function (here the constructor), even tho is an Array of String, it is different than the type of a class variable, which is also defined as Array of String. The reason, as I understand is :
The former is an array of unspecified length, but immutable (Open Array)
The later is a mutable array of unspecified length that can add or remove elements (Dynamic Array).
Even tho, both are Array of String, we need a method to differentiate these. So, the current syntax of Lazarus / FPC requires the mutable class variable to have a different type signature.
This is done by creating a new type which is also an Array of String, and then setting the class variable to this type.
TStringArray = Array of String;
I do not understand the complete story here. But I am told in the forum, that this is the syntax now, and people use autopilot to work through this.
Okey .......
















