-
Notifications
You must be signed in to change notification settings - Fork 7
TResult
Ivan Semenkov edited this page Jan 27, 2021
·
2 revisions
TResult contains value or error type like in GO or Rust languages. It is exists specialized TVoidResult type which no have value.
uses
utils.result;
type
generic TResult<T, E> = class
A new result type can be created by using one of constructors.
Create new result contains value.
constructor CreateValue (AValue : V);
uses
utils.result;
type
TIntResult = {$IFDEF FPC}type specialize{$ENDIF} TResult<Integer, String>;
var
res : TIntResult;
begin
res := TIntResult.CreateValue(12);
FreeAndNil(res);
end;
Create new result contains error.
constructor CreateError (AError : E);
uses
utils.result;
type
TIntResult = {$IFDEF FPC}type specialize{$ENDIF} TResult<Integer, String>;
var
res : TIntResult;
begin
res := TIntResult.CreateError('something wrong');
FreeAndNil(res);
end;
Return true if result contains value.
function IsOk : Boolean;
uses
utils.result;
type
TIntResult = {$IFDEF FPC}type specialize{$ENDIF} TResult<Integer, String>;
var
res : TIntResult;
begin
res := TIntResult.CreateValue(12);
if res.IsOk then
;
FreeAndNil(res);
end;
Return true if result contains error.
function IsErr : Boolean;
uses
utils.result;
type
TIntResult = {$IFDEF FPC}type specialize{$ENDIF} TResult<Integer, String>;
var
res : TIntResult;
begin
res := TIntResult.CreateError('something wrong');
if res.IsErr then
;
FreeAndNil(res);
end;
Return value if not exists raise TValueNotExistsException.
function Value : V;
Raised when trying to get a value that does not exist.
TValueNotExistsException = class(Exception)
uses
utils.result;
type
TIntResult = {$IFDEF FPC}type specialize{$ENDIF} TResult<Integer, String>;
var
res : TIntResult;
begin
res := TIntResult.CreateValue(12);
writeln(res.Value);
FreeAndNil(res);
end;
Return error if not exists raise TErrorNotExistsException.
function Error : E;
Raised when trying to get a error that does not exist.
TErrorNotExistsException = class(Exception)
uses
utils.result;
type
TIntResult = {$IFDEF FPC}type specialize{$ENDIF} TResult<Integer, String>;
var
res : TIntResult;
begin
res := TIntResult.CreateError('something wrong');
writeln(res.Error);
FreeAndNil(res);
end;