operator ~ method
Executes the prefixed function, propagating any unwrapped Err() values to the return value of the function.
Shortcut for propagateResult.
Usage:
// This function will error at runtime if passed an Err() value
Result<int, String> add(Result<int, String> a, Result<int, String> b) {
return Ok(a.unwrap() + b.unwrap());
}
// For safety, it can be rewritten as:
Result<int, String> add(Result<int, String> a, Result<int, String> b) => ~() {
return Ok(a.unwrap() + b.unwrap());
// You can also use the ~ operator as a shortcut for unwrap():
// return Ok(~a + ~b);
};
// Runtime safety achieved from a mere 8 total characters of syntactical overhead!
Note: This operator returns dynamic
. Consider explicitly typing receivers
of this operation to limit the amount of dynamic
being passed around in
your codebase.
If this operator were typed to return Result<T, E> and you were to return Ok() or Err() in the prefixed function, the compiler would treat the operator as returning Result<T, dynamic> or Result<dynamic, E>.
Operators are not able to receive generic type parameters and thus this operator is unable to infer the generic types of the returned Result in the same way propagateResult can.
// Compiles fine
Result<int, String> foo = propagateResult(() => Ok(1));
// If this operator were typed to return Result<T, E>:
// Error: A value of type 'Result<int, dynamic>' can't be assigned to a variable of type 'Result<int, String>'
Result<int, String> bar = ~() => Ok(1);
// The only way around this would be to explicitly specify the type parameters
// on the returned result like:
Result<int, String> baz = ~() => Ok<int, String>(1);
// And that's not very ergonomic when you are already likely to type your
// variables and function/method returns
Hence, this operator returns dynamic
to avoid this problem. The compiler
will still enforce returning Result
values regardless, as this operator
is only provided for functions which return Result
.
If a dynamic
return value is undesireable to you, consider using
propagateResult directly instead.
Implementation
operator ~() => propagateResult(this);