BREAKING CHANGE: feat: use 'is empty' instead of 'has value'

This commit is contained in:
Kyle Ratti 2024-04-30 13:36:31 -04:00
parent 479b30b60a
commit 69d582c0ed
No known key found for this signature in database
GPG Key ID: 4D429B6287C68DD9
2 changed files with 16 additions and 8 deletions

View File

@ -26,7 +26,7 @@ public class MaybeExtensionTests
public void MaybeNullableTests() public void MaybeNullableTests()
{ {
Assert.IsNull(Maybe.Empty<int>().ToNullable()); Assert.IsNull(Maybe.Empty<int>().ToNullable());
Assert.IsNull(Maybe.Create(0, hasValue: _ => false).ToNullable()); Assert.IsNull(Maybe.Create(0, evalIsEmpty: () => true).ToNullable());
} }
[Test] [Test]

View File

@ -4,20 +4,25 @@ using System;
public static class Maybe public static class Maybe
{ {
public static Maybe<T> Create<T>(T value) => new(value, hasValue: true); public static Maybe<T> Create<T>(T value) => new(value);
public static Maybe<T> Create<T>(T value, Func<T, bool> hasValue) => new(value, hasValue: hasValue(value));
public static Maybe<T> Empty<T>() => new(val: default!, hasValue: false); public static Maybe<T> Create<T>(T value, Func<bool> evalIsEmpty) =>
evalIsEmpty()
? Empty<T>()
: new Maybe<T>(value);
public static Maybe<T> Empty<T>() => new();
} }
public readonly record struct Maybe<T> public readonly record struct Maybe<T>
{ {
private readonly T _value; private readonly T _value;
public readonly bool HasValue; public bool HasValue { get; }
internal Maybe(T val, bool hasValue) internal Maybe(T val) : this()
{ {
_value = val; _value = val;
HasValue = hasValue; HasValue = true;
} }
public T Value public T Value
@ -77,7 +82,10 @@ public readonly record struct Maybe<T>
? default ? default
: (TOutput)Convert.ChangeType(Value, t); : (TOutput)Convert.ChangeType(Value, t);
return Maybe.Create(output, hasValue: _ => output != null)!; if (output == null)
return Maybe.Empty<TOutput>();
return Maybe.Create(output);
} }
catch (InvalidCastException) catch (InvalidCastException)
{ {