Delphi has an option to exit with a value (Example: Exit(0);), but how do I exit with a value if the return value is a record?
TIntResult = record
Value: Integer;
Error: String;
end;
function GetCount: TIntResult;
begin
if not IsLoggedIn then
Exit(Value: 0; Error: 'Not logged in'); // I want this
if not IsAdmin then
Exit(TIntResult(Value: 0; Error: 'Not Admin')); // or this
...
end;
CodePudding user response:
Of course, you can always use the Result
variable and Exit
.
But if you want to use the Delphi 2009 Exit(...)
syntax -- without giving it a TIntResult
-typed variable --, the two most obvious options are these:
Using a constructor
type
TIntResult = record
Value: Integer;
Error: string;
constructor Create(AValue: Integer; const AError: string);
end;
{ TIntResult }
constructor TIntResult.Create(AValue: Integer; const AError: string);
begin
Value := AValue;
Error := AError;
end;
Then you can do:
function Test: TIntResult;
begin
// ...
Exit(TIntResult.Create(394, 'Invalid page.'));
end;
Using a TIntResult
-returning function
function IntRes(AValue: Integer; const AError: string): TIntResult;
begin
Result.Value := AValue;
Result.Error := AError;
end;
Then you can do:
function Test: TIntResult;
begin
// ...
Exit(IntRes(394, 'Invalid page.'));
end;