carbonteq /FP

Cheatsheet — Unwrap & safety

Extract values from Option and Result safely with unwrap, safeUnwrap, and unwrapErr.

Extraction operators let you get the inner value out of an Option or Result. Use them at boundaries (UI, I/O, tests) rather than in the middle of pipelines.

Extraction operators

OperatorDescriptionUsage
unwrapGet inner value; throws if empty/err (Option & Result)
.unwrap() → value | throws
safeUnwrapGet inner value or null (no throw) (Option & Result)
.safeUnwrap() → value | null
unwrapErrGet error value; throws if Ok (Result only)
.unwrapErr() → error | throws
unwrapOrGet inner value or fallback (Option & Result)
.unwrapOr(fallback) → value
unwrapOrElseGet inner value or compute fallback (Option & Result)
.unwrapOrElse(fn) → value

Guidance

  • Prefer staying in the pipeline (map/flatMap/match*) and only extract at boundaries (UI, I/O, tests).
  • If you must extract, prefer safeUnwrap() or unwrapOr() for non-exceptional flows.
  • Use unwrap() only when you're certain the value exists (e.g., after an isOk() check).

On this page