Skip to content

TResult

Ivan Semenkov edited this page Jan 27, 2021 · 2 revisions

Table of contents

About

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

Create

A new result type can be created by using one of constructors.

CreateValue

Create new result contains value.

constructor CreateValue (AValue : V);
Example
uses
  utils.result;
  
type
  TIntResult = {$IFDEF FPC}type specialize{$ENDIF} TResult<Integer, String>;

var
  res : TIntResult;
  
begin
  res := TIntResult.CreateValue(12);
  
  FreeAndNil(res);
end;

CreateError

Create new result contains error.

constructor CreateError (AError : E);
Example
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;

IsOk

Return true if result contains value.

function IsOk : Boolean;
Example
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;

IsErr

Return true if result contains error.

function IsErr : Boolean;
Example
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;

Value

Return value if not exists raise TValueNotExistsException.

function Value : V;

TValueNotExistsException

Raised when trying to get a value that does not exist.

TValueNotExistsException = class(Exception)
Example
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;

Error

Return error if not exists raise TErrorNotExistsException.

function Error : E;

TErrorNotExistsException

Raised when trying to get a error that does not exist.

TErrorNotExistsException = class(Exception)
Example
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;
Clone this wiki locally