Reason
  • Документация
  • Попробовать
  • API
  • Сообщество
  • Блог
  • Languages iconРусский
    • 日本語
    • English
    • Deutsch
    • Español
    • Français
    • 한국어
    • Português (Brasil)
    • Українська
    • 中文
    • 繁體中文
    • Помочь с переводом
  • GitHub

›Основы языка

Введение

  • Что и зачем

Установка

  • Установка
  • Плагины для редакторов и IDE

Основы языка

  • Обзор
  • Let Bindings
  • Primitives
  • Basic Structures
  • Types
  • Records
  • Variants
  • Options and nullability
  • Functions
  • Recursion
  • Деструктуризация
  • Pattern Matching
  • Mutable Bindings
  • Loops
  • Modules

Advanced Features

  • JSX
  • External
  • Исключения
  • Объекты

JavaScript

  • Взаимодействие с JavaScript
  • Шпаргалка по синтаксису
  • Pipe First
  • Промис
  • Библиотеки
  • Конвертация из JS

Дополнительно

  • Часто задаваемые вопросы (FAQ)
  • Дополнительные инструменты
Translate

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