4

I have a class like this:

Programmer = Class(Worker)
private
  // Some code here
  programmingLanguages: array of String;
  numOfProgrammingLanguages: integer;
public
  // Some code here
  procedure SetProgrammingLanguages(newLanguages: array of String);
  function GetNumOfProgrammingLanguages(languages: array of string) : integer;
end;

When I write the following code for the SetProgrammingLanguages method, I get an error:

procedure Programmer.SetProgrammingLanguages(newLanguages: array of String);
begin
  programmingLanguages := newLanguages;
end;

Incompatible types: 'Dynamic array' and 'array of string'

How can I resolve this problem?

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Alexander Seredenko
  • 799
  • 3
  • 9
  • 26
  • Please read my [article about open array parameters](http://rvelthuis.de/articles/articles-openarr.html). It might help. – Rudy Velthuis Mar 22 '16 at 11:02

1 Answers1

4

The solution is to first declare a new type, say TProgrammingLanguages = array of string;. Then use that in both the class declaration and in the method parameter.

The method parameter as you have it written now is an open array parameter which is different from the dynamic array type you use for the programminglanguages field.

To learn about Open array parameters see the documentation.

Tom Brunberg
  • 20,312
  • 8
  • 37
  • 54
  • Tnx, It works for me. – Alexander Seredenko Mar 21 '16 at 19:32
  • That is a risky solution. You will now have two references to the same object. The asker might prefer copy semantics. – David Heffernan Mar 21 '16 at 19:40
  • @DavidHeffernan Could you propose better solution? – Alexander Seredenko Mar 21 '16 at 19:42
  • 3
    It depends on what you want to achieve. You might want to take another reference, in the knowledge that assigning to `programmingLanguages[i]` will modify the object that the caller has a reference to. Or you might want to take a copy. You might prefer to use an open array because it offers more flexibility in what you can pass. If you do that, then you should declare the arg as `const` to avoid making an unnecessary copy. We can tell you why the compiler reports that error, but I honestly don't feel we can advise you on what your code should be. Not without details of what the problem is. – David Heffernan Mar 21 '16 at 20:19