Record TOptional

Unit

Declaration

type TOptional<T> = record

Description

A generic record that holds an optional (nullable) value of type T.

This type is inspired by Java's Optional type and is useful for indicating the presence or absence of a value, avoiding the need for sentinel values like 0 or empty string for non-nullable types.

Overview

Methods

Public class function From(Value: T): TOptional<T>; static;
Public class function Empty: TOptional<T>; static;
Public function Get: T;
Public function TryGet(out Value: T): Boolean;
Public function OrElse(Default: T): T;
Public function OrElseGet(Supplier: TFunc<T>): T;
Public procedure IfPresent(Consumer: TProc<T>);
Public class operator Implicit(Value: T): TOptional<T>; inline;

Properties

Public property IsPresent: Boolean read FIsPresent;
Public property IsEmpty: Boolean read GetIsEmpty;

Description

Methods

Public class function From(Value: T): TOptional<T>; static;

Creates an instance of TOptional with a value.

Parameters
Value
The value to hold.
Returns

A TOptional with a value present

Public class function Empty: TOptional<T>; static;

Creates an empty TOptional.

Returns

A TOptional with no value present

Public function Get: T;

Returns the held value if it is present, otherwise raises an EOptionalError if the optional is empty.

Returns

The held value

Exceptions raised
EOptionalError
If the optional is empty.
Public function TryGet(out Value: T): Boolean;

Tries to get the held value if it is present, returning True if successful.

Parameters
Value
The out parameter that will contain the value if successful
Returns

True if the value is present, False otherwise

Public function OrElse(Default: T): T;

Returns the held value if present, otherwise returns the provided default value.

Parameters
Default
The value to return if the optional is empty
Returns

The held value if present, or the provided default value

Public function OrElseGet(Supplier: TFunc<T>): T;

Returns the held value if present, otherwise returns the value supplied by the provided supplier function.

Parameters
Supplier
A function that provides the default value if the optional is empty
Returns

The held value if present, or the value supplied by the provided function

Public procedure IfPresent(Consumer: TProc<T>);

Executes the provided consumer procedure if the value is present.

Parameters
Consumer
A procedure to execute if the value is present
Public class operator Implicit(Value: T): TOptional<T>; inline;

Implicit conversion operator to allow assigning a value of type T directly to TOptional.

Parameters
Value
The value to convert to TOptional.
Returns

A TOptional holding the provided value.

Properties

Public property IsPresent: Boolean read FIsPresent;

Indicates whether the value is present.

Public property IsEmpty: Boolean read GetIsEmpty;

Indicates whether the optional is empty.


Generated by PasDoc 0.16.0-snapshot.