Optional

public enum Optional[T]: not Copyable where T: not Static

Cases

case None

The absent state — same shape as a null reference, but checked at the type level.

case Some(T)

Wraps a present value of T.

Initializers

public init()

Compiler-emitted bridge for the null literal. Always constructs .None.

Methods

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 copy
public func contains(T) -> Bool

True 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); // false
public func expect(String) -> T

Like 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]

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 }; // None
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); // None
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(); // None
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

True when this is .None. The complement of isSome.

public func isSome() -> Bool

True when this is .Some. Cheap discriminator-only check.

Examples

Some(42).isSome(); // true None.isSome(); // false
public func isSomeAnd((T) -> Bool) -> Bool

True 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 }; // false
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]

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]

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, preferred
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]

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]

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]

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]

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 None
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]

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")); // None
public func unwrap() -> T

Returns 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(); // PANIC
public func unwrap(or: T) -> T

Returns 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); // 0
public func unwrap(orElse: () -> T) -> T

Like 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 fn
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, preferred
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); // None
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")); // None

ImplementsEquatable

Associated Types

type Output = Bool

Methods

public func equal(to: Self) -> Bool

Bridges Equal.equal(to:) to Equatable.isEqual(to:).

public func isEqual(to: Optional[T]) -> Bool

Structural equality on the optional. Backs ==.

Examples

Some(1) == Some(1); // true Some(1) == Some(2); // false Some(1) == None; // false None == None; // true
public func notEqual(to: Self) -> Bool

Default !=: delegates to == so there's a single source of truth.

ImplementsComparable

Associated Types

type Output = Bool

Methods

public func compare(Optional[T]) -> Ordering

Three-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); // false
public func greaterThan(Self) -> Bool

> derived from compare.

public func greaterThanOrEqual(Self) -> Bool

>= derived from compare.

public func isAtLeast(Self) -> Bool

start.. lower-bound check, derived from compare.

public func isAtMost(Self) -> Bool

..=end upper-bound check, derived from compare.

public func isBelow(Self) -> Bool

..<end upper-bound check, derived from compare.

public func lessThan(Self) -> Bool

< derived from compare.

public func lessThanOrEqual(Self) -> Bool

<= derived from compare.

ImplementsHashable

Methods

public func hash[H](into: mutating H) where H: Hasher

Mixes 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 = T
type Output = T
type Residual = ()

Methods

public consuming func tryExtract() -> ControlFlow[T, ()]

Drives tryContinue(value) for Some, Break(()) for None.

ImplementsForceUnwrap

Associated Types

type Output

Methods

public consuming func forceUnwrap() -> T

Returns the wrapped value, trapping on .None. Backs value!.

ImplementsFromResidual

Methods

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]

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)

Renders Some(...) or None, forwarding options to the inner format for the payload.

public func formatted(FormatOptions) -> String

Returns 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()

Builds the absent/none instance.

ImplementsCoalesce

Associated Types

type Output

Methods

public func coalesce(() -> T) -> T

Returns 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