英文:
Fold either to return different value
问题
我有一个类似这样的 Vavr Either:
Either<DomainError, Boolean> maybePendingPayment = ...
我想将这个响应进行折叠,以返回 Either<DomainError, Optional<GenericType>>:
return maybePendingPayment.fold(
domainError -> domainError,
pendingPayment -> pendingPayment ? GenericType.builder().build() : Optional.empty()
)
但是看起来我似乎不能这样做,因为 fold 要求我返回相同的类型:
[ERROR] 下限: io.vavr.control.Either<xxx.yyy.DomainError, java.util.Optional<xxx.yyy.GenericType>>, java.lang.Object
[ERROR] 下限: java.util.Optional<T>, java.util.Optional<T>, xxx.yyy.DomainError
有没有比仅通过 if-else 检查左右两侧的方式更高级的方法来实现这一点?
英文:
I have a Vavr Either that looks like this:
Either<DomainError, Boolean> maybePendingPayment = ...
I want to fold this response to return Either<DomainError, Optional<GenericType>>
return maybePendingPayment.fold(domainError -> domainError, pendingPayment ? GenericType.builder().build() : Optional.empty())
But it doesn't look like I can do this because fold wants me to return the same types:
[ERROR] lower bounds: io.vavr.control.Either<xxx.yyy.DomainError,java.util.Optional<xxx.yyy.GenericType>>,java.lang.Object
[ERROR] lower bounds: java.util.Optional<T>,java.util.Optional<T>,xxx.yyy.DomainError
Is there any way I can do this in a fancier way than just checking the left and right sides with an if-else?
答案1
得分: 2
应用 fold
到你的 Either
上将会(正如名称所示)对其进行折叠,并应用左侧或右侧函数,返回应用函数的结果。
通过以下示例,我尝试更清楚地说明正在发生的情况:
public Optional<Object> verify() {
Either<DomainError, Boolean> maybePendingPayment = Either.right(true);
return maybePendingPayment.fold(Optional::of, pendingPayment -> pendingPayment ? Optional.of("pending payment") : Optional.empty());
}
正如你所见,我选择了 Optional<Object>
作为函数的返回类型,并且也将 fold 的左侧函数包装在了一个 Optional 中。在解包 Either
时,你的返回类型将是 Optional<DomainError>
或者右侧函数的结果(在我的示例中是 String
或 Optional.empty
)。如果在你尝试返回的内容之间存在一个共同的超类型(在 GenericType
和 DomainError
之间),你可以选择将其作为函数的返回类型,而不是选择 Object
。
英文:
Applying fold
to your Either
will (as the name already suggests) fold it and apply either the left or right function, returning the result of the applied function.
With the following example I tried to make more clear what is happening:
public Optional<Object> verify() {
Either<DomainError, Boolean> maybePendingPayment = Either.right(true);
return maybePendingPayment.fold(Optional::of, pendingPayment -> pendingPayment ? Optional.of("pending payment") : Optional.empty());
}
As you can see I chose Optional<Object>
for the functions return type and wrapped the left function of the fold in an Optional as well. When unwrapping the Either
your return type will either be the Optional<DomainError>
or the result of the right function (in my example String
or Optional.empty
). If there is a common Supertype to what you are trying to return (between GenericType
and DomainError
), you could choose this one as a return type of the function instead of Object
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论