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.
In Python, we can assign a function to a variable. And using that variable we can call the function as many as times we want. Thereby, increasing code reusability. Simply assign a function to the desired variable but without () i.e. just with the name of the function.
So yes there are stack or local variables to a specified scope resolution.
A return is a value that a function returns to the calling script or function when it completes its task. A return value can be any one of the four variable types: handle, integer, object, or string. The type of value your function returns depends largely on the task it performs.
To return a value from a function, you must include a return statement, followed by the value to be returned, before the function's end statement. If you do not include a return statement or if you do not specify a value after the keyword return, the value returned by the function is unpredictable.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With