-
Notifications
You must be signed in to change notification settings - Fork 7
TOptional
Ivan Semenkov edited this page Jan 27, 2021
·
2 revisions
TOptional class type can contains some value or none, like in Rust language.
uses
utils.optional;
type
generic TOptional<T> = class
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;
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);
uses
utils.optional;
type
TIntOptional = {$IFDEF FPC}type specialize{$ENDIF} TOptional<Integer>;
var
intOpt : TIntOptional;
begin
intOpt := TIntOptional.Create(12);
FreeAndNil(intOpt);
end;
Checking if optional contains value.
function IsSome : Boolean;
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;
Return stored value or raise TNoneValueException exeption if none.
function Unwrap : T;
Raised when trying to get a value that does not exist.
uses
utils.optional;
type
TNoneValueException = class(Exception)
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;