diff --git a/Remora.Rest.Core/Optional.cs b/Remora.Rest.Core/Optional.cs index df81341..22fa68f 100644 --- a/Remora.Rest.Core/Optional.cs +++ b/Remora.Rest.Core/Optional.cs @@ -152,7 +152,7 @@ public bool TryGet([MaybeNullWhen(false)] out TValue value) /// Applies a mapping function to the value of the if it has one; otherwise, returns /// a new of the resulting type with no value. /// - /// The mapping function. + /// The mapping function, returning . /// The value type for the output of the mapping result. /// /// A new optional with the mapping result if has a value; an optional with no value @@ -165,6 +165,23 @@ public Optional Map(Func mappingFunc) : default(Optional); } + /// + /// Applies a mapping function to the value of the if it has one; otherwise, returns + /// a new of the resulting type with no value. + /// + /// The mapping function, returning . + /// The value type for the output of the mapping result. + /// + /// A new optional with the mapping result if has a value; an optional with no value + /// otherwise. + /// + public Optional FlatMap(Func> mappingFunc) + { + return this.HasValue + ? mappingFunc(_value) + : default; + } + /// /// Implicitly converts actual values into an optional. /// diff --git a/Tests/Remora.Rest.Core.Tests/Optional/OptionalTests.cs b/Tests/Remora.Rest.Core.Tests/Optional/OptionalTests.cs index 40808be..64e69f8 100644 --- a/Tests/Remora.Rest.Core.Tests/Optional/OptionalTests.cs +++ b/Tests/Remora.Rest.Core.Tests/Optional/OptionalTests.cs @@ -734,6 +734,27 @@ public static void ReturnsOptionalWithNoValueIfInputHasNoValue() } } + public static class FlatMap + { + private static Optional ParseInt(string s) => int.TryParse(s, out int i) ? i : default(Optional); + + [Fact] + public static void CanFlatMap() + { + Optional one = "1"; + var flatMapped = one.FlatMap(ParseInt); + Assert.Equal(new Optional(1), flatMapped); + } + + [Fact] + public static void ReturnsOptionalWithNoValueIfInputHasNoValue() + { + var a = default(Optional); + var flatMapped = a.FlatMap(ParseInt); + Assert.False(flatMapped.HasValue); + } + } + public static class ConvertNullToEmpty { public static class Struct