Search code examples
functiondelphivariablesfunction-pointersanonymous-methods

How to assign a function, returned by another function, to a function variable? The result rather than the generating function itself


A function is returning an anonymous function. I would like to assign the result to a variable. However the compiler thinks that I am trying to assign the function and not the result of the function. How can I resolve this?

program Project9;

{$APPTYPE CONSOLE}

type
  TMyEvent = reference to function: string;

var
  v1: TMyEvent;

function GetHandler: TMyEvent;
begin
  Result := function: string
            begin
              Result := '';
            end;
end;

begin
  v1 := GetHandler;  // <- Incompatible types: 'TMyEvent' and 'Procedure'
end.

Note: I do have a workaround but I hope that this problem can be solved without introducing a wrapper:

program Project9;

{$APPTYPE CONSOLE}

type
  TMyEvent = reference to function: string;

  TWrapper = record
    FHandler: TMyEvent;
  end;

var
  v1: TMyEvent;

function GetHandler: TWrapper;
begin
  Result.FHandler := function: string
                     begin
                       Result := '';
                     end;
end;

begin
  v1 := GetHandler.FHandler;  // <- works

EDIT: this is not specific to anonymous or any special kind of functions: that is actual for any function returning the function, it was the same in Turbo Pascal before even the 1st Delphi arrived.


Solution

  • If your anonymous methods/functions are paramless, you must assign with ();

    v1 := GetHandler();
    

    Without the parentheses Delphi will try to assign the function to the variable. The parens tell it to invoke the function and assign the function result to the variable.