I am converting code from Lazarus to Delphi 10.4 Sydney and have a line that throws an error:
// Split line and put it into a new array, txtDataArray
txtDataArray := txtToParse.Split(['.', ',', '!'], TStringSplitOptions.ExcludeEmpty);
txtToParse
is comma delimited text variable.
How would I correctly write that to work in Delphi 10.4 Sydney?
I tried this and I get an error that states:
Incompatible Types - a Dynamic Array and System TArray<System String> at line 340:
Under var
I have:
// For splitting
charArray : Array[0..2] of Char;
txtToParse : String;
txtArray : array of String;
Then in the main function I have:
// Split line and put it into a new array, txtArray
charArray[0] := '.';
charArray[1] := ',';
charArray[2] := '!';
txtArray := txtToParse.Split(charArray);
How can I get this to work in Delphi 10.4 Sydney?
CodePudding user response:
You need to change this declaration:
txtArray : array of String;
To this:
txtArray : TArray<String>;
The reason is explained in detail in the documentation:
Type Compatibility and Identity (Delphi)
And in particular:
Arrays are assignment-compatible only if they are of the same type. Because the Delphi language uses name-equivalence for types, the following code will not compile.
var Int1: array[1..10] of Integer; Int2: array[1..10] of Integer; ... Int1 := Int2;
To make the assignment work, declare the variables as:
var Int1, Int2: array[1..10] of Integer;
or:
type IntArray = array[1..10] of Integer; var Int1: IntArray; Int2: IntArray;
And
Overloads and Type Compatibility in Generics
Two non-instantiated generics are considered assignment compatible only if they are identical or are aliases to a common type.
Two instantiated generics are considered assignment compatible if the base types are identical (or are aliases to a common type) and the type arguments are identical.
In FreePascal, Split()
returns a TStringArray
which is a plain vanilla alias for array of string
, and so is assignment-compatible with an array of string
variable.
But in Delphi, Split()
returns a TArray<String>
, which is a Generic alias for array of T
where T
is string
, so it is a distinct Generic type, and thus is not assignment-compatible with an array of String
variable, only with a TArray<String>
variable.