Search code examples
delphifunctionconstantsdelphi-6

Const function in Delphi


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.


Solution

  • 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;