Bind chain with different return type
theodorehook opened this issue · comments
Hello good people
I have a seemingly simple scenario that I can't seem to find an easy answer for. Consider the following
public static Result<decimal, Error> GetSomething(decimal? example) =>
GetGivenOrDefault(example)
.Bind(DoSomething)
.Bind(DoSomethingAndReturnTheThingOrError);
The implementation is irrelevant but the signatures would be:
public static Result<decimal> GetGivenOrDefault(decimal? example)
public static Result<decimal> DoSomething(decimal example)
public static Result<decimal, Error> DoSomethingAndReturnTheThingOrError(decimal example)
The intermediate results should be Result<decimal>
only the final function should return Result<decimal, Error>
The compiler complains DoSomethingAndReturnTheThingOrError has the wrong return type. If I change all signatures to Result<decimal, Error> of course it's all fine but I don't want to have to do this unless really necessary.
I have tried multiple things with Map, Match and several other methods, all to no avail. It must be a common enough scenario, what am I missing here? Many thanks.
You should provide error mapping from "string" to "Error".
Something like this:
public static Result<decimal, Error> GetSomething(decimal? example) =>
GetGivenOrDefault(example)
.Bind(DoSomething)
.MapError(error => new Error(error))
.Bind(DoSomethingAndReturnTheThingOrError);
I knew it would be simple. That worked, thanks very much.