Skip to content

Commit a596241

Browse files
committed
Added Flatten method to unwrap the optional
1 parent e3997c4 commit a596241

File tree

2 files changed

+17
-0
lines changed

2 files changed

+17
-0
lines changed

src/DotNext.Tests/OptionalTests.cs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -352,4 +352,11 @@ public static void ConcatTwoValues()
352352
optional = Optional<int>.None.Concat<long>(42L);
353353
False(optional.HasValue);
354354
}
355+
356+
[Fact]
357+
public static async Task FlattenTask()
358+
{
359+
await ThrowsAsync<InvalidOperationException>(static () => Task.FromResult(Optional.None<int>()).Flatten());
360+
Equal(42, await Task.FromResult(Optional.Some(42)).Flatten());
361+
}
355362
}

src/DotNext/Optional.cs

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,16 @@ public static class Optional
3636
public static async Task<T?> Or<T>(this Task<Optional<T>> task, T? defaultValue)
3737
=> (await task.ConfigureAwait(false)).Or(defaultValue);
3838

39+
/// <summary>
40+
/// Returns a task that contains unwrapped value; or exception if <see cref="Optional{T}"/> has no value.
41+
/// </summary>
42+
/// <param name="task">The task representing optional value.</param>
43+
/// <typeparam name="T">The type of the value.</typeparam>
44+
/// <returns>The task containing a value of type <typeparamref name="T"/>; or the exception if <see cref="Optional{T}"/> has no value.</returns>
45+
/// <exception cref="InvalidOperationException">No value is present.</exception>
46+
public static async Task<T> Flatten<T>(this Task<Optional<T>> task)
47+
=> (await task.ConfigureAwait(false)).Value;
48+
3949
/// <summary>
4050
/// If a value is present, apply the provided mapping function to it, and if the result is
4151
/// non-null, return an Optional describing the result. Otherwise, returns <see cref="Optional{T}.None"/>.

0 commit comments

Comments
 (0)