Option<T>

Control Flow

IsSomeAnd

Use IsSomeAnd when you want to check if the Option is a Some and that the value contained inside the Some matches a predicate.

Option<string> maybeName = Option.Some("Raven");
maybeName.IsSomeAnd(name => name.Length > 0); // true

IsNoneOr

Use IsNoneOr when you want to check if the Option is a None or the value contained inside the Some matches a predicate.

Option<string> maybeName = Option.Some("Queen");
maybeName.IsNoneOr(name => name.Length > 0); // true
maybeName.IsNoneOr(name => string.IsNullOrWhiteSpace(name)); // false

Transform

Refer to the Transform section on the Core Functionality page to learn about the other transform methods available for an Option<T>

FlatMap

Use FlatMap to compose monadic pipelines where each operation might fail and return an Option<T> itself. It prevents nested Option<Option<T>> results and keeps the pipeline flat and clean.

Without FlatMap, you'd need to Map and then flatten manually, or deal with nested options.

FlatMap short-circuits: if one of the options in the chain is None, the subsequent functions are skipped.

Filter

Use Filter to retain only the values that pass a predicate. If the value doesn't match, the result becomes a None.

This is the clean alternative to if-guards. It keeps the monadic flow and makes intent obvious.

Zip

Use Zip to combine two options into a single option containing both values as a tuple.

If either Option being zipped is a None, then a None will be returned.

ZipWith

Use ZipWith to combine two options into a single option using a custom zipping function.

If either Option being zipped is a None, then a None will be returned.

Unzip

Reverses a Zip, splitting the tuple into two options.

Logical Operators

Sometimes you want to combine two Option values using logical operators without leaving the monadic model.

Or

Or returns the first Some value encountered in the chain.

Use Or when you want a prioritized fallback chain

OrElse

Like Or, but lazily evaluated. The fallback is only invoked if the preceding is None.

Xor

Xor is an exclusive-or. It returns the first Some value encountered in the chain if exactly one of the options is Some.

Xor is niche, but useful when you're checking mutually exclusive conditions

Last updated

Was this helpful?