Const function in Delphi
Asked Answered
W

2

5

In the Delphi code I am looking at I've found the following set of lines:

const
    function1: function(const S: String): String = SomeVariable1;
    function2: function(const S: String): String = SomeVariable2;

What is this doing? I mean, not the actual code within the functions, but what does it do to declare a function inside the const section and compare(?) it with a variable value? I'm assuming the single equals is a comparison since that's what it is everywhere else in Delphi.

Thank you.

Wallop answered 7/4, 2011 at 15:29 Comment(1)
Andreas explained what this is. However I can't see what this is for. Do you have "Assignable typed constants" enabled in the project?Apostil
N
20

No, the equals is an assignment, as this is how constants are assigned. Consider, for example,

const Pi = 3.1415;

or

const s = 'This is an example';

There are also 'typed constants':

const Pi: extended = 3.1415;

In your snippet above, we define a typed constant that holds a function of signature function(const S: String): String. And we assign the (compatible) function SomeVariable1 to it.

SomVariable1 has to be defined earlier in the code, for instance, as

function SomeVariable1(const S: String): String;
begin
  result := S + '!';
end;

Consider the following example:

function SomeVariable1(const S: String): String;
begin
  result := S + '!';
end;

const
  function1: function(const S: String): String = SomeVariable1;

procedure TForm1.FormCreate(Sender: TObject);
begin
  caption := function1('test');
end;
Nepenthe answered 7/4, 2011 at 15:34 Comment(0)
W
8

Andreas's answer covers the technical bits very well, but I'd like to provide an answer to this part:

What is this doing?

More along the lines of Why use this weired-looking construct? I can think of two reasons:

  • The code is written with {$J+} (assignable typed constants), and the "constant" is assigned a different value at some point. If function1 were declared as a variable, the initialization would need to be done in the initialization section of the unit, and that might be too late (if some other unit's initialization section runs before this one and attempts calling the function1 "function")
  • Used if the function name was changed from function1 to SomeVariable1 and there's 3rd party code that can't easily be changed. This provides a one-line way of declaring the alias.
Whitechapel answered 7/4, 2011 at 16:2 Comment(1)
It looks like the second bullet point is right judging from a quick search of the project without finding the function name SomeVariable1.Wallop

© 2022 - 2024 — McMap. All rights reserved.