Reason
  • Docs
  • Try
  • API
  • Community
  • Blog
  • Languages iconEnglish
    • 日本語
    • Deutsch
    • Español
    • Français
    • 한국어
    • Português (Brasil)
    • Русский
    • Українська
    • 中文
    • 繁體中文
    • Help Translate
  • GitHub

›Language Basics

Intro

  • What & Why

Setup

  • Installation
  • Editor Plugins

Language Basics

  • Overview
  • Let Bindings
  • Primitives
  • Basic Structures
  • Types
  • Records
  • Variants
  • Options and nullability
  • Functions
  • Recursion
  • Destructuring
  • Pattern Matching
  • Mutable Bindings
  • Loops
  • Modules

Advanced Features

  • JSX
  • External
  • Exception
  • Object

JavaScript

  • Interop
  • Syntax Cheatsheet
  • Pipe First
  • Promise
  • Libraries
  • Converting from JS

Extra

  • Frequently Asked Questions
  • Extra Goodies
Edit

Options and nullability

Quick overview: Options

Options are a built-in variant that represent the presence or absence of a value. It is similar to the concept of "nullable" values in other languages. Options are used often.

In Reason there is no "null" value that any type might assume. Instead if a value needs to communicate that it might (or might not) be available, then the option type is used.

Definition

The option type is a variant with two constructors:

  • Some represents the presence of a value and accepts that value as an argument
  • None represents the absence of a value and acceps no arguments
type option('value) =
  | None
  | Some('value);

Note: This type is already defined and automatically available for use everywhere.

Examples

It is common for None to be the default value before something is setup.

type person = {
  name: string,
  age: int,
};

let nobody: option(person) = None;

Logging in can set up the user's data:

let login = () =>
  Some({
    name: "Alice",
    age: 42,
  });

let alice = login();

Now when writing functions that deal with users we must make sure that there is actually a user present:

let happyBirthday = (user) => {
  switch (user) {
  | Some(person) => "Happy birthday " ++ person.name
  | None => "Please login first"
  };
};
← VariantsFunctions →
  • Definition
  • Examples