Option
The Option module provides utilities for working with optional values. Option types represent values that may or may not exist, providing a safer alternative to null values.
Constructors
Options are created using the Some and None constructors,
which are pre-registered in Kit and available without import.
Constructors
Some
a -> Option a
Wraps a value in a Some, indicating the value exists.
value = Some 42
name = Some "Alice"
None
Option a
Represents the absence of a value.
empty = None
Predicates
Option.is-some?
Option a -> Bool
Returns
true if the option contains a value.
println (Option.is-some? (Some 42))
# => true
println (Option.is-some? None)
# => false
Option.is-none?
Option a -> Bool
Returns
true if the option is empty.
println (Option.is-none? None)
# => true
println (Option.is-none? (Some 42))
# => false
is-some?
a -> Bool
Bare function that checks if a value is a Some variant.
println (is-some? (Some "hello"))
# => true
is-none?
a -> Bool
Bare function that checks if a value is None.
println (is-none? None)
# => true
Transforming
Option.map
(a -> b) -> Option a -> Option b
Applies a function to the value inside a Some, or returns None if empty.
double = fn(x) => x * 2
result = Option.map double (Some 21)
# => Some(42)
empty = Option.map double None
# => None
Option.and-then
(a -> Option b) -> Option a -> Option b
Chains optional operations. If the input is Some, applies the function which may return None.
Also known as "flatMap" or "bind" in other languages.
parse-positive = fn(s) =>
match String.to-int s
| Some n if n > 0 -> Some n
| _ -> None
result = Some "42" |> Option.and-then parse-positive
# => Some(42)
invalid = Some "-5" |> Option.and-then parse-positive
# => None
Unwrapping
Option.unwrap
Option a -> a
Returns the value inside a Some. Raises an error if None.
Prefer
Option.unwrap-or or pattern matching when possible.
value = Option.unwrap (Some 42)
# => 42
# This will raise an error:
# Option.unwrap None
Option.unwrap-or
a -> Option a -> a
Returns the value inside a Some, or the provided default if None.
value = Option.unwrap-or 0 (Some 42)
# => 42
default = Option.unwrap-or 0 None
# => 0
Pattern Matching with Options
Options are typically handled using pattern matching:
describe = fn(opt) =>
match opt
| Some value -> "Got: ${value}"
| None -> "Nothing"
println (describe (Some 42))
# => "Got: 42"
println (describe None)
# => "Nothing"