unwrap abstract method
Strongly discouraged: Unsafely returns the contained value.
This method is the equivalent of the !
(bang) operator for nullable
types. It subverts the safety provided by the Outcome by throwing an
exception instead of allowing you to handle the failure state through
the type system. A thrown exception from unwrap()
should be considered a
critical programming error.
⚠️ DANGER
This method will throw an Err if the Outcome is in a failure state (Err or None).
Prefer Safer Alternatives:
1. To handle both success and failure cases:
Use pattern matching with a switch
expression. This is the most
idiomatic and safest way to handle all possibilities.
// For a Result<T>
switch (myResult) {
case Ok(value: final data):
print('Success: $data');
case Err(error: final e):
print('Failure: $e');
}
// For an Option<T>
switch (myOption) {
case Some(value: final data):
print('Found: $data');
case None():
print('Not found.');
}
2. To provide a fallback value:
Use unwrapOr to safely get the value or a default if it's absent.
final user = findUser(id).unwrapOr(GuestUser());
3. To perform a side-effect only on success:
Use ifOk()
or ifSome()
to run code without breaking the chain.
When is it okay to use unwrap()
?
The only acceptable time is within a test or a trusted context where a
failure is a logic bug that should crash the test or program.
Even then, it is best to wrap it in an UNSAFE
block to signal this
explicit breach of safety.
final value = UNSAFE(() => Ok(1).unwrap()); // Signals deliberate unsafe access
Implementation
@override
@unsafeOrError
T unwrap();