Skip to content

TOptional

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

Table of contents

About

TOptional class type can contains some value or none, like in Rust language.

uses
  utils.optional;
  
type
  generic TOptional<T> = class

Create

A new optional value can be created by call its constructor.

Use the following constructor to create a new TOptional of type None.

constructor Create;
Example
uses
  utils.optional;
  
type
  TIntOptional = {$IFDEF FPC}type specialize{$ENDIF} TOptional<Integer>;

var
  intOpt : TIntOptional;
  
begin
  intOpt := TIntOptional.Create;

  FreeAndNil(intOpt);
end;

Use the following constructor to create a new TOptional with a value.

 constructor Create (AValue : T);
Example
uses
  utils.optional;
  
type
  TIntOptional = {$IFDEF FPC}type specialize{$ENDIF} TOptional<Integer>;

var
  intOpt : TIntOptional;
  
begin
  intOpt := TIntOptional.Create(12);

  FreeAndNil(intOpt);
end;

IsSome

Checking if optional contains value.

function IsSome : Boolean;
Example
uses
  utils.optional;
  
type
  TIntOptional = {$IFDEF FPC}type specialize{$ENDIF} TOptional<Integer>;

var
  intOpt : TIntOptional;
  
begin
  intOpt := TIntOptional.Create;
  if intOpt.IsSome then
    ;

  FreeAndNil(intOpt);
end;

Unwrap

Return stored value or raise TNoneValueException exeption if none.

function Unwrap : T;

TNoneValueException

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

uses
  utils.optional;

type
  TNoneValueException = class(Exception)
Example
uses
  utils.optional;
  
type
  TIntOptional = {$IFDEF FPC}type specialize{$ENDIF} TOptional<Integer>;

var
  intOpt : TIntOptional;
  
begin
  intOpt := TIntOptional.Create;
  writeln(intOpt.Unwrap);

  FreeAndNil(intOpt);
end;
Clone this wiki locally