Skip to content

Optional

Type

NPL does not have null, but in practice it is not always possible to assign meaningful values to everything immediately. For such cases there is Optional<T>. Optional<T> is a native NPL union type between Some<T> and None, where T is the type of the wrapped item (which can be of any type).

Optionals are instantiated using optionalOf.

Accessing the value of an Optional<> is accomplished through getOrFail() or getOrElse(), whereas inspecting whether it contains a value is accomplished through isPresent() (see Methods section below). Additionally, pattern matching can be done via match.

Note that it is considered best practice to always initialize variables with meaningful values when possible.

Methods

computeIfAbsent

<function> Returns the value of an optional if present, or returns a computed result if empty. The computation is not invoked if the optional is not empty, making this is a lazy alternative to Optional<T>.getOrElse.

Receiver

Optional<T>

Type Arguments

T - the optional's payload

Arguments

default - () -> T - function or closure that returns the value in case the optional is empty

Returns

T - the optional's value if present, or the computed result if empty

Usage

// If the Optional is empty, the value lazily
// computed by the provided function is returned.
optionalOf<Number>().computeIfAbsent(function() -> 42) == 42
// If the Optional is *not* empty,
// the Optional's payload is returned.
optionalOf(21).computeIfAbsent(function() -> 42) == 21

getOrElse

<function> Returns the value inside the optional if present, or the default value otherwise.

Receiver

Optional<T>

Type Arguments

T

Arguments

default - T - value to return if optional contains no value

Returns

T - the value inside the optional if present, otherwise default

Usage

optionalOf<Number>(42).getOrElse(1) == 42
optionalOf<Number>().getOrElse(1) == 1

getOrFail

<function> Returns the value inside the optional if present, or causes a runtime error otherwise.

Receiver

Optional<T>

Type Arguments

T

Returns

T

Usage
optionalOf<Number>().getOrFail() // Throws a run-time exception

isPresent

<function> Returns true if a value is present in the optional, and false otherwise.

Receiver

Optional<T>

Type Arguments

T

Returns

Boolean - true if a value is present in the optional, otherwise false

Usage

optionalOf<Number>(42).isPresent() == true
optionalOf<Number>().isPresent() == false

Inherited methods

toText

<function> Obtain the Text representation of this.

Receiver

T

Type Arguments

T

Returns

Text - the Text representation of this

Usage

Converts an Optional<T> to Text.

optionalOf<Number>(42).toText() == "/lang/core/Some<Number> { result: 42 }"
optionalOf<Number>().toText() == "/lang/core/None {  }"