Optional
public enum Optional[T]: not Copyable where T: not StaticCases
case None
case NoneThe absent state — same shape as a null reference, but checked at the type level.
case Some(T)
case Some(T)Wraps a present value of T.
Initializers
public init()
public init()Compiler-emitted bridge for the null literal. Always constructs
.None.
Methods
public func clone() -> Optional[T]
public func clone() -> Optional[T]Returns an independent copy. For value types this is a shallow copy of the payload; for COW types, the underlying buffer is shared until first mutation.
Examples
let opt = Some([1, 2, 3]);
let copy = opt.clone(); // independent copypublic func contains(T) -> Bool
public func contains(T) -> BoolTrue when self is Some and the wrapped value equals value.
Slightly cheaper than == Some(value) when you already have the
bare value.
Examples
Some(42).contains(42); // true
Some(42).contains(0); // false
None.contains(42); // falsepublic func expect(String) -> T
public func expect(String) -> TLike unwrap, but the panic carries message instead of the
generic text. Use this where the absence of a value should crash
loudly with context.
Errors
Panics with message on .None via fatalError.
Examples
let cfg = loadConfig().expect("Config file required");
public func filter((T) -> Bool) -> Optional[T]
public func filter((T) -> Bool) -> Optional[T]Returns Some(value) when the predicate accepts the value, None
otherwise.
Examples
Some(4).filter { it % 2 == 0 }; // Some(4)
Some(3).filter { it % 2 == 0 }; // None
None.filter { it % 2 == 0 }; // Nonepublic func flatMap[U]((T) -> Optional[U]) -> Optional[U]
public func flatMap[U]((T) -> Optional[U]) -> Optional[U]Monadic bind — apply a transform that itself returns an
Optional, without nesting. Equivalent to map(...).flatten().
Examples
func parse(s: String) -> Int64? { ... }
Some("42").flatMap(parse); // Some(42)
Some("abc").flatMap(parse); // None (parse failed)
None.flatMap(parse); // Nonepublic func flatten[U]() -> Optional[U] where T == Optional[U]
public func flatten[U]() -> Optional[U] where T == Optional[U]Collapses an Optional[Optional[T]] one level. Available only
when T is itself an Optional.
Examples
Some(Some(42)).flatten(); // Some(42)
Some(None).flatten(); // None
None.flatten(); // Nonepublic func inspect((T) -> ()) -> Optional[T]
public func inspect((T) -> ()) -> Optional[T]Side-effecting tap — runs fn on the wrapped value (if any) and
returns self unchanged. Useful for logging or assertions inside
a chain.
Examples
getUser(id)
.inspect { print("Found: \{it.name}") }
.map { it.email };public func isNone() -> Bool
public func isNone() -> BoolTrue when this is .None. The complement of isSome.
public func isSome() -> Bool
public func isSome() -> BoolTrue when this is .Some. Cheap discriminator-only check.
Examples
Some(42).isSome(); // true
None.isSome(); // falsepublic func isSomeAnd((T) -> Bool) -> Bool
public func isSomeAnd((T) -> Bool) -> BoolTrue when .Some(value) and predicate(value) returns true.
None always answers false without invoking the predicate.
Examples
Some(42).isSomeAnd { it > 0 }; // true
Some(-1).isSomeAnd { it > 0 }; // false
None.isSomeAnd { it > 0 }; // falsepublic func iter() -> OptionalIterator[T]
public func iter() -> OptionalIterator[T]Returns an OptionalIterator that yields one element if Some or
zero elements if None. Lets an optional plug into any for-in
or iterator-combinator pipeline.
Examples
for value in Some(42).iter() {
print(value) // prints 42
};
for value in None.iter() {
print(value) // never executes
};public func map[U]((T) -> U) -> Optional[U]
public func map[U]((T) -> U) -> Optional[U]Functor map — applies transform to the wrapped value, leaving
None untouched.
Examples
Some(2).map { it * 2 }; // Some(4)
None.map { it * 2 }; // None
Some("hello").map { it.len }; // Some(5)public static func none() -> Optional[T]
public static func none() -> Optional[T]Returns .None. Prefer the null literal — it works in any
optional context without naming the type parameter.
Examples
let a = Optional[Int64].none(); // None
let b: Int64? = null; // identical, preferredpublic func okOr[E](E) -> Result[T, E]
public func okOr[E](E) -> Result[T, E]Promotes to Result, supplying error for the None branch.
error is eagerly evaluated — use okOrElse to defer it.
Examples
Some(42).okOr("missing"); // Ok(42)
None.okOr("missing"); // Err("missing")public func okOrElse[E](() -> E) -> Result[T, E]
public func okOrElse[E](() -> E) -> Result[T, E]Like okOr, but error() is only invoked on None.
Examples
Some(42).okOrElse { NotFoundError() }; // Ok(42), fn not called
None.okOrElse { NotFoundError() }; // Err(NotFoundError())public func orElse(() -> Optional[T]) -> Optional[T]
public func orElse(() -> Optional[T]) -> Optional[T]Returns self when Some, otherwise the result of alternative().
For "use a default scalar" prefer the ?? operator; reach for
orElse when the fallback itself is an Optional.
Examples
Some(1).orElse { Some(2) }; // Some(1), fn not called
None.orElse { Some(2) }; // Some(2)
None.orElse { loadFromCache() }; // calls fn
// For unwrapping with a default, prefer ??:
let value = optionalInt ?? 0;public mutating func replace(T) -> Optional[T]
public mutating func replace(T) -> Optional[T]Stores value and returns whatever was there before. Mirror of
take for the assignment direction.
Examples
var opt = Some(1);
opt.replace(2); // Some(1); opt is now Some(2)
var none: Int64? = null;
none.replace(1); // None; none is now Some(1)public mutating func take() -> Optional[T]
public mutating func take() -> Optional[T]Removes and returns the current value, leaving self as None.
Idiomatic for "consume once" optional fields.
Examples
var opt = Some(42);
opt.take(); // Some(42); opt is now None
opt.take(); // None; opt is still Nonepublic mutating func take(where: (T) -> Bool) -> Optional[T]
public mutating func take(where: (T) -> Bool) -> Optional[T]Conditional take — empties self and returns the value only when
predicate(value) accepts it. Otherwise leaves self untouched
and returns None.
Examples
var opt = Some(42);
opt.take(where: { it > 0 }); // Some(42); opt is now None
var opt2 = Some(42);
opt2.take(where: { it < 0 }); // None; opt2 is still Some(42)public func then[U](Optional[U]) -> Optional[U]
public func then[U](Optional[U]) -> Optional[U]Returns other when self is Some, otherwise None. other is
evaluated eagerly — use flatMap for lazy chaining.
Examples
Some(1).then(Some("a")); // Some("a")
Some(1).then(None); // None
None.then(Some("a")); // Nonepublic func unwrap() -> T
public func unwrap() -> TReturns the wrapped value, panicking if None. Reach for
unwrap(or:), the ?? operator, or pattern matching unless
you can prove the value is Some.
Errors
Panics with "called unwrap() on None" when invoked on .None.
Examples
Some(42).unwrap(); // 42
None.unwrap(); // PANICpublic func unwrap(or: T) -> T
public func unwrap(or: T) -> TReturns the wrapped value or default when None. default is
always evaluated — use unwrap(orElse:) if computing it is
expensive.
Examples
Some(42).unwrap(or: 0); // 42
None.unwrap(or: 0); // 0public func unwrap(orElse: () -> T) -> T
public func unwrap(orElse: () -> T) -> TLike unwrap(or:), but defaultFn is only called on None. Use this
when the default is expensive to compute or has side effects.
Examples
Some(42).unwrap(orElse: { expensiveDefault() }); // 42, no call
None.unwrap(orElse: { expensiveDefault() }); // calls fnpublic static func wrap(T) -> Optional[T]
public static func wrap(T) -> Optional[T]Wraps value in .Some. Rarely needed in practice — bare values
are promoted via FromValue, and let x: Int64? = 42 does the
right thing.
Examples
let opt = Optional.wrap(42); // Some(42)
let opt: Int64? = 42; // identical, preferredpublic func xor(Optional[T]) -> Optional[T]
public func xor(Optional[T]) -> Optional[T]Exclusive-or of presence — returns the unique Some when exactly
one of self/other is set, else None.
Examples
Some(1).xor(None); // Some(1)
None.xor(Some(2)); // Some(2)
Some(1).xor(Some(2)); // None
None.xor(None); // Nonepublic func zip[U](with: Optional[U]) -> Optional[(T, U)]
public func zip[U](with: Optional[U]) -> Optional[(T, U)]Pairs two optionals into an optional tuple. Some only when both
inputs are Some.
Examples
Some(1).zip(with: Some("a")); // Some((1, "a"))
Some(1).zip(with: None); // None
None.zip(with: Some("a")); // NoneImplementsEquatable
Associated Types
type Output = Bool
type Output = BoolMethods
public func equal(to: Self) -> Bool
public func equal(to: Self) -> BoolBridges Equal.equal(to:) to Equatable.isEqual(to:).
public func isEqual(to: Optional[T]) -> Bool
public func isEqual(to: Optional[T]) -> BoolStructural equality on the optional. Backs ==.
Examples
Some(1) == Some(1); // true
Some(1) == Some(2); // false
Some(1) == None; // false
None == None; // truepublic func notEqual(to: Self) -> Bool
public func notEqual(to: Self) -> BoolDefault !=: delegates to == so there's a single source of truth.
ImplementsComparable
Associated Types
type Output = Bool
type Output = BoolMethods
public func compare(Optional[T]) -> Ordering
public func compare(Optional[T]) -> OrderingThree-way compare. None < Some(_); two Somes defer to the
inner compare.
Examples
None < Some(1); // true
Some(1) < Some(2); // true
Some(2) < Some(1); // falsepublic func greaterThan(Self) -> Bool
public func greaterThan(Self) -> Bool> derived from compare.
public func greaterThanOrEqual(Self) -> Bool
public func greaterThanOrEqual(Self) -> Bool>= derived from compare.
public func isAtLeast(Self) -> Bool
public func isAtLeast(Self) -> Boolstart.. lower-bound check, derived from compare.
public func isAtMost(Self) -> Bool
public func isAtMost(Self) -> Bool..=end upper-bound check, derived from compare.
public func isBelow(Self) -> Bool
public func isBelow(Self) -> Bool..<end upper-bound check, derived from compare.
public func lessThan(Self) -> Bool
public func lessThan(Self) -> Bool< derived from compare.
public func lessThanOrEqual(Self) -> Bool
public func lessThanOrEqual(Self) -> Bool<= derived from compare.
ImplementsHashable
Methods
public func hash[H](into: mutating H) where H: Hasher
public func hash[H](into: mutating H) where H: HasherMixes a one-byte tag (0 for None, 1 for Some) into the
hasher, then defers to T.hash for the payload.
ImplementsTryable
Associated Types
type Output = T
type Output = Ttype Output = T
type Output = Ttype Output = T
type Output = Ttype Residual = ()
type Residual = ()Methods
public consuming func tryExtract() -> ControlFlow[T, ()]
public consuming func tryExtract() -> ControlFlow[T, ()]Drives try — Continue(value) for Some, Break(()) for None.
ImplementsForceUnwrap
Associated Types
type Output
type OutputMethods
public consuming func forceUnwrap() -> T
public consuming func forceUnwrap() -> TReturns the wrapped value, trapping on .None. Backs value!.
ImplementsFromResidual
Methods
public static func fromResidual(consuming ()) -> Optional[T]
public static func fromResidual(consuming ()) -> Optional[T]Builds .None from the residual produced by a try short-circuit.
ImplementsFromValue
Methods
public static func from(consuming T) -> Optional[T]
public static func from(consuming T) -> Optional[T]Wraps value in .Some. Called by the compiler at the promotion
site, not usually by user code. consuming so value is moved into
.Some (no clone-and-leak of a borrowed original).
ImplementsFormattable
Methods
public func format(into: mutating StringBuilder, FormatOptions)
public func format(into: mutating StringBuilder, FormatOptions)Renders Some(...) or None, forwarding options to the inner
format for the payload.
public func formatted(FormatOptions) -> String
public func formatted(FormatOptions) -> StringReturns this value rendered as a String.
Convenience wrapper: creates a StringBuilder, calls
format(into:), and returns the built string. Uses a distinct
name to avoid overload-resolution ambiguity with format(into:).
ImplementsExpressibleByNullLiteral
Initializers
init()
init()Builds the absent/none instance.
ImplementsCoalesce
Associated Types
type Output
type OutputMethods
public func coalesce(() -> T) -> T
public func coalesce(() -> T) -> TReturns the wrapped value or evaluates default(). The default is
only invoked on None, which is what makes ?? cheap on the
happy path.
Defined in lang/std/result/optional.ks