If I want to create a getter accessor for a method variable, the getter does not give back the variable, but it executes the code referenced by the variable.
unit Unit5;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;
type
TMyFactory1 = function : TObject of object;
TMyFactory2 = reference to function : TObject;
TForm5 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
fMyFactory1 : TMyFactory1;
fMyFactory2 : TMyFactory2;
public
{ Public declarations }
function getMyFactory1 : TMyFactory1;
function getMyFactory2 : TMyFactory2;
end;
var
Form5: TForm5;
implementation
{$R *.dfm}
function TForm5.getMyFactory1 : TMyFactory1;
begin
result := fMyFactory1;
end;
function TForm5.getMyFactory2 : TMyFactory2;
begin
result := fMyFactory2;
end;
procedure TForm5.Button1Click(Sender: TObject);
var
aMF1 : TMyFactory1;
aMF2 : TMyFactory2;
begin
aMF1 := getMyFactory1; // Incompatible types: 'TObject' and 'TMyFactory1'
aMF2 := getMyFactory2; // Incompatible types: 'TMyFactory2' and 'Procedure of object'
end;
end.
I can create a setter for this type but I am unable to create a getter. How can I create it?
Just add parentheses at the end of the function call. In this way you are informing the compiler that you want to store the functions in the variables. Otherwise you are going to execute the functions and assign their results to the variables.
var
aMF1 : TMyFactory1;
aMF2 : TMyFactory2;
begin
aMF1 := getMyFactory1();
aMF2 := getMyFactory2();
end;