3

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; 
Lieven Keersmaekers
  • 57,207
  • 13
  • 112
  • 146
iamjoosy
  • 3,299
  • 20
  • 30

2 Answers2

12

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;
kludg
  • 27,213
  • 5
  • 67
  • 118
  • Thanks Serg. It was exactly these two () I was looking for. Soemtimes things are so easy .. if you know them. – iamjoosy May 07 '10 at 13:21
  • 1
    That's why I always use C's calling syntax (aka () parenthesis) to make it clear when it's a call. – alex May 07 '10 at 16:32
0

The only way I've found to work around this is to declare your GetListener like this:

procedure GetListener(var a: TPropertyChangedListener);

There might be some syntax to force the compiler to consider the function's result instead of the function itself, but I couldn't find any.

Ken Bourassa
  • 6,363
  • 1
  • 19
  • 28
  • Well, yes, I thought about that solution myself. The drawback is, that it makes the code a bit dirtier - especially since in my real code I want to add the GetListener result into a TList. In that case I would need to declare an extra variable, get the Listener as you suggested, and add the variable to the list instead of MyList.Add(GetListener) – iamjoosy May 07 '10 at 12:46