Grav v1.14.0

Optional

import "std/core" (included in import "std") · namespace std.core

Optional<T> is a box that holds a value or nothing: an explicit alternative to returning a "magic" value like -1 or "" for "no result". It works for any T, including classes and structs. Its methods let you use the value without checking by hand.

grav
import "std"

fn findUser(id: int) -> Optional<string> {
    if (id == 1) { return new Optional<string>("ada") }
    return new Optional<string>()
}

fn main() {
    let found = findUser(1)
    let missing = findUser(2)
    print(found.isPresent())
    print(missing.getOr("nobody"))
    print(found.map(fn(n: string) => Str.upper(n)).get())
    found.ifPresent(fn(n: string) { print("hello ${n}") })
    print(found.filter(fn(n: string) => n.length > 5).isEmpty())
}
Output
true
nobody
ADA
hello ada
true

Grav has two other ways to express "maybe a value": the built-in nullable types T? (checked by the compiler), and the data enum Option<T>, which works with match. See Null safety for when to use which.

API

class Optional<T>

Constructors

  • new Optional()
  • new Optional(value: T)

Methods

  • fn isPresent() -> bool — Whether there is a value.
  • fn isEmpty() -> bool — Whether there is no value.
  • fn get() -> T — The value (StateError when empty).
  • fn getOr(fallback: T) -> T — The value, or fallback when empty.
  • fn ifPresent(f: fn(T)) — Calls f with the value, if there is one.
  • fn map<U>(f: fn(T) -> U) -> Optional<U> — An Optional of f(value), or an empty one.
  • fn filter(pred: fn(T) -> bool) -> Optional<T> — This Optional when its value passes pred, else an empty one.

Edit this page on GitHub