Skip to content

Option

Deprecated type (since 2021.1.23, to be removed in 2023.3.0)

The Option type will no longer be supported. Please use Optional instead.

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 Option<T>.

Options are instantiated using optionOf.

Accessing the value of an Option<> is accomplished through getOrFail() or getOrElse(), whereas inspecting whether it contains a value is accomplished through isPresent() (see Methods section below).

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

Methods

computeIfAbsent (deprecated)

Deprecated: Use Optional.computeIfAbsent

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

Receiver

Option<T>

Type Arguments

T - the option's payload

Arguments

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

Returns

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

Usage

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

getOrElse (deprecated)

Deprecated: Use Optional.getOrElse

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

Receiver

Option<T>

Type Arguments

T

Arguments

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

Returns

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

Usage

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

getOrFail (deprecated)

Deprecated: Use Optional.getOrFail

<function> Returns the value inside the option if present, or causes runtime error 27 -- Empty option otherwise.

Receiver

Option<T>

Type Arguments

T

Returns

T

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

isPresent (deprecated)

Deprecated: Use Optional.isPresent

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

Receiver

Option<T>

Type Arguments

T

Returns

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

Usage

optionOf<Number>(42).isPresent() == true
optionOf<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 Option<T> to Text.