Option type

Also known as: Maybe type

On this page 7

An option type is a type that represents an optional value: a value of the option type either contains exactly one value of an underlying type or contains nothing. In functional programming it is the standard, type-safe alternative to null references, and it is also known as the Maybe type in Haskell and related languages.

The type is usually defined as an algebraic data type with two cases, such as Some(x) and None in OCaml, Rust and Scala, or Just x and Nothing in Haskell. Because absence is encoded in the type itself, the compiler can require every caller to handle the empty case before using the value.

How an option type encodes absence

An option type is a sum type with two variants. One variant wraps a present value, the other carries no data. A function that may fail to produce a result, such as a dictionary lookup or parsing a number from text, returns Option<T> instead of T, and the signature itself documents that the result can be missing.

The decisive property is that Option<T> and T are different types. Code cannot call a string method on an Option<String> directly; it must first unpack the value, typically with pattern matching. That requirement moves a large class of failures, the null pointer dereference, from run time to compile time.

LanguageType namePresent caseAbsent case
HaskellMaybe aJust xNothing
RustOption<T>Some(x)None
OCaml and F#'a optionSome xNone
ScalaOption[A]Some(x)None
SwiftOptional<T> or T?.some(x).none or nil
JavaOptional<T>Optional.of(x)Optional.empty()
Option type names and variants across languages

Combinators for working with optional values

Unpacking with an explicit match at every step quickly becomes verbose, so option types come with higher-order combinators that transform the value only when it is present. These operations make the option type a functor and a monad, which allows chains of fallible steps to be written as a single pipeline.

The most important combinators are map, which applies a function inside the option, and flatMap (called and_then in Rust and >>= in Haskell), which chains a function that itself returns an option. If any step yields None, the whole chain short-circuits to None without further checks.

CombinatorInput when presentInput when absentTypical use
mapApplies function, wraps resultStays absentTransform a found value
flatMap or bindApplies option-returning functionStays absentChain fallible lookups
filterKeeps value if predicate holdsStays absentReject invalid values
getOrElse or unwrap_orReturns inner valueReturns a defaultProvide a fallback
orElseReturns itselfTries an alternative optionFallback source of data
Common combinators and their behavior

Languages with do-notation or similar syntax hide the chaining further. In Rust, the ? operator returns early from a function when an option is None, and in Haskell a do block over Maybe reads like straight-line code while still propagating absence automatically.

The option type solves the same problem as a null reference, but with a crucial difference: null is a member of every reference type, so any variable might be null and the compiler cannot tell. Tony Hoare, who introduced null references in ALGOL W, later called them his billion-dollar mistake because of the defects they caused.

ApproachAbsence visible in typeCompiler forces handlingCarries error detail
Null referenceNoNoNo
Sentinel value such as -1NoNoNo
Nullable type such as `String?`YesYes, in Kotlin and C#No
Option typeYesYesNo
Result or Either typeYesYesYes
Ways of representing a possibly missing value

Nullable types in Kotlin, Swift and C# with nullable reference types achieve similar safety through flow analysis, though they do not nest: String?? collapses in some languages, whereas Option<Option<T>> remains meaningful. When the caller needs to know why a value is missing, a Result or Either type is the better choice, because the option type deliberately carries no explanation.

Representation and cost at run time

An option type does not have to cost more than a nullable pointer. Rust applies the null pointer optimization: Option<&T> and Option<Box<T>> occupy the same space as a plain pointer, with the all-zero bit pattern representing None. For other payloads, the compiler adds a small discriminant tag, usually one byte padded to alignment.

Managed languages differ. Scala and Java allocate a wrapper object for each present value, which adds heap allocation and indirection in hot loops, while Swift and Haskell compilers often eliminate the wrapper after inlining. Performance-sensitive Java code therefore avoids Optional in fields and collections and uses it mainly as a return type.

Design guidelines and common mistakes

The benefit of an option type disappears when code escapes the type system by force-unwrapping. Calling unwrap() in Rust, get() on a Java Optional or fromJust in Haskell reintroduces a run-time crash on the absent case, so such calls belong only where absence is genuinely impossible and documented.

SituationRecommended choiceReason
Lookup may find nothingReturn an optionAbsence is normal, not an error
Operation can fail for several reasonsReturn a ResultCaller needs the cause
Value always present after validationUse the plain typeAvoid needless unwrapping
Optional field in a data modelOption in the field typeDocuments the schema precisely
Optional function argument in JavaOverload or default insteadOptional parameters are discouraged
Situations and recommended handling
  • Prefer map and flatMap chains over nested matches when only the present case does real work.
  • Never return null from a function whose type is an option; that defeats the guarantee.
  • Convert to a Result with a clear message when the absence must be reported upward.

In simple terms

An option type is like a box that is either full or empty, with a label on the outside saying it might be empty. Before using what is inside, the program has to open the box and check.

Older approaches handed over the contents directly. Sometimes they gave nothing at all, without warning. The program would then crash when it reached for something missing. With an option type, the possibility of nothing is announced in advance. The language refuses to continue until the empty case has a plan.

A practical example

A payments team writes a service in Rust that looks up a customer’s preferred currency. The customer record comes from a cache, the currency field is optional, and the exchange rate for that currency may not be loaded yet. Each of the three lookups returns an Option.

Instead of three nested null checks, the developer writes one chain: find the customer, then and_then the currency field, then and_then the rate table, and finally unwrap_or the default rate for US dollars. The ? operator handles a fourth step inside a helper function. The compiler rejects an early draft that forgot the case of a customer without a currency, before the code ever reaches testing.

After release, the service processes several million requests per day with zero null-related crashes, while a comparable older service written with nullable references had logged dozens of such incidents per quarter. The explicit types also make code review faster, because every possible absence is visible in the signatures.