diff --git a/Railway/ResultExtensions.cs b/Railway/ResultExtensions.cs index 58925e7..34576c5 100644 --- a/Railway/ResultExtensions.cs +++ b/Railway/ResultExtensions.cs @@ -2,6 +2,80 @@ namespace Just.Railway; public static partial class ResultExtensions { + #region Match (with fallback) + + public static T Match(this in Result result, Func fallback) + { + return result.State switch + { + ResultState.Success => result.Value, + ResultState.Error => fallback(result.Error!), + _ => throw new ResultNotInitializedException(nameof(result)) + }; + } + + public static async Task Match(this Result result, Func> fallback) + { + return result.State switch + { + ResultState.Success => result.Value, + ResultState.Error => await fallback(result.Error!).ConfigureAwait(false), + _ => throw new ResultNotInitializedException(nameof(result)) + }; + } + public static async Task Match(this Task> resultTask, Func fallback) + { + var result = await resultTask.ConfigureAwait(false); + return result.State switch + { + ResultState.Success => result.Value, + ResultState.Error => fallback(result.Error!), + _ => throw new ResultNotInitializedException(nameof(resultTask)) + }; + } + public static async Task Match(this Task> resultTask, Func> fallback) + { + var result = await resultTask.ConfigureAwait(false); + return result.State switch + { + ResultState.Success => result.Value, + ResultState.Error => await fallback(result.Error!).ConfigureAwait(false), + _ => throw new ResultNotInitializedException(nameof(resultTask)) + }; + } + + public static async ValueTask Match(this Result result, Func> fallback) + { + return result.State switch + { + ResultState.Success => result.Value, + ResultState.Error => await fallback(result.Error!).ConfigureAwait(false), + _ => throw new ResultNotInitializedException(nameof(result)) + }; + } + public static async ValueTask Match(this ValueTask> resultTask, Func fallback) + { + var result = await resultTask.ConfigureAwait(false); + return result.State switch + { + ResultState.Success => result.Value, + ResultState.Error => fallback(result.Error!), + _ => throw new ResultNotInitializedException(nameof(resultTask)) + }; + } + public static async ValueTask Match(this ValueTask> resultTask, Func> fallback) + { + var result = await resultTask.ConfigureAwait(false); + return result.State switch + { + ResultState.Success => result.Value, + ResultState.Error => await fallback(result.Error!).ConfigureAwait(false), + _ => throw new ResultNotInitializedException(nameof(resultTask)) + }; + } + + #endregion + #region Merge public static Result Merge(this IEnumerable results)