Search code examples
delphidelphi-2009anonymous-methods

Anonymous method as function result


What I want to do is to assign an anonymous method which I get as a function result to a variable of the same type. Delphi complains about not beeing able to do the assignement. Obviously Delphi things I want to assign the "GetListener" function instead of the result of that same function. Any help with this is very much appreciated.

type
      TPropertyChangedListener = reference to procedure (Sender: TStimulus);

      TMyClass = class
        function GetListener:TPropertyChangedListener
      end;


    ....

    var MyClass: TMyClass;
        Listener: TPropertyChangedListener;
    begin
      MyClass:= TMyClass.create;
      Listener:= MyClass.GetListener;   //  Delphi compile error: E2010 Incompatible types:  TPropertyChangedListener' and 'Procedure of object' 

    end; 

Solution

  • Use the following syntax:

      Listener:= MyClass.GetListener();
    

    I have written the following example to make clear the difference between the MyClass.GetListener() and MyClass.GetListener assignments:

    type
      TProcRef = reference to procedure(Sender: TObject);
      TFunc = function: TProcRef of object;
    
      TMyClass = class
        function GetListener: TProcRef;
      end;
    
    function TMyClass.GetListener: TProcRef;
    begin
      Result:= procedure(Sender: TObject)
      begin
        Sender.Free;
      end;
    end;
    
    procedure TForm1.Button1Click(Sender: TObject);
    var
      MyClass: TMyClass;
      ProcRef: TProcRef;
      Func: TFunc;
    
    begin
      MyClass:= TMyClass.Create;
    // standard syntax
      ProcRef:= MyClass.GetListener();
    
    // also possible syntax
    //  Func:= MyClass.GetListener;
    //  ProcRef:= Func();
    
      ProcRef(MyClass);
    end;