Reputation: 1113
I want to write a procedure that appends to an array of Integer, but Delphi IDE gives me compile-time error 'Incompatyble types'. This is my code :
procedure appendToIntegerArray(var intArr : array of Integer; valueToAppend : Integer);
var
counter : Integer;
begin
counter := Length(intArr);
SetLength(intArr, counter + 1); // This is where it gives me the compile-time error
intArr[counter] := valueToAppend;
end;
Can anyone help me fix my procedure ?
Upvotes: 4
Views: 6719
Reputation: 84550
It's one of the quirks of Delphi's syntax: declaring an array of whatever
as a function parameter does not define it as an array like you might think, but as an open array, a "magic" type that can accept any array of the correct base type. If you want to use a specific type of array, you need a named type.
This is the sort of thing that the generic TArray<T>
was designed for. Make your parameter a TArray<integer>
if you can. If not, consider updating to a newer version of Delphi (you're missing out on a whole lot if you're still on an older version!) and in the meantime, declare an array type like so:
type
TMyIntegerArray = array of integer;
And use that type as your parameter type, rather than declaring array of integer
there.
Upvotes: 5
Reputation: 612954
You are facing the error because SetLength
operates on dynamic arrays and that is not a dynamic array. That is an open array parameter.
You'll need to use a dynamic array instead:
procedure appendToIntegerArray(var intArr: TArray<Integer>; valueToAppend: Integer);
....
If you use an older Delphi that does not support generic arrays, you'll need to declare a type for the array:
type
TIntegerArray = array of Integer;
procedure appendToIntegerArray(var intArr: TIntegerArray; valueToAppend: Integer);
....
Or you could use the type declared in the RTL, TIntegerDynArray
. This type is declared in the Types
unit.
One of the irritations of Delphi's type system is that a type like TIntegerArray
is not assignment compatible with, say, TIntegerDynArray
because they are distinct types. That makes it harder than it should be to work with code that uses distinct array types. One of the great benefits of generic arrays is that the rules for type compatibility of generics are a little more forgiving. So, if you can use TArray<T>
, do so.
If you are appending item by item, then I would generally suggest that a list class would be better. In this case you would use TList<Integer>
and simply call its Add
method.
Upvotes: 6