Nesting and conversion
Remove a level of nesting, or convert to an Option.
Flatten and Transpose are extension methods, in Waystone.Monads.Results.Extensions — add the using. GetOk and GetErr are on Result<TOk, TErr> itself and need nothing.
Flatten
Result<TOk, TErr> Flatten<TOk, TErr>(this Result<Result<TOk, TErr>, TErr> result)Removes one level of nesting. You get here by calling Map with a function that itself returns a Result.
Result<string, string> start = Result.Ok<string, string>("Storm Weaver");
Result<Result<int, string>, string> output = start.Map(x => CountRunes(x));
Result<int, string> flattened = output.Flatten();Prefer AndThen, which does both steps at once. This exists for code that grew one method at a time.
Transpose
Option<Result<TOk, TErr>> Transpose<TOk, TErr>(this Result<Option<TOk>, TErr> result)Turns a result holding an option into an option holding a result.
Result<Option<decimal>, string> calculationResult =
CreateCalculator(Realm.TalDorei)
.Map(calculator => calculator.GetToll(100.00m));
Option<Result<decimal, string>> maybeToll = calculationResult.Transpose();Calling Transpose here declares that the absence of a toll is a valid outcome in your business rules.
On an Err: you get Some(Err(…)) — the failure survives.
Option<Result<T, E>> transposes the other way. See the Option page.
GetOk
Converts to an Option, keeping the success value and discarding the error.
The error is gone. Use this only when you have already dealt with it, or do not care.
GetErr
The other direction. Keeps the error and discards the success value.
Going the other way
To convert an Option into a Result, see OkOr and OkOrElse.
Last updated
Was this helpful?