如何解决同时使用Vavr的“左”和“右”吗?
如何以功能性方式使用vavr Either的“左”或“右”?
我有一个返回Either<RuntimeException,String>
的方法。根据此结果,我需要执行对我们报告库的回调,例如reportSuccess()
或reportFailure()
。因此,我正在寻找一种不错的,实用的方法。如果一个Either
有一个biConsumer(Consumer<? super L> leftConsumer,Consumer<? super R> rightConsumer
,我可以这样写:
Either<RuntimeException,String> result = // get the result from somewhere
result.biConsumer(ex -> {
reportFailure();
},str -> {
repportSuccess();
});
到目前为止,我找到的最接近的解决方法是biMap()方法,它看起来像
Either<RuntimeException,String> mappedResult = result.bimap(ex -> {
reportFailure();
return ex;
},str -> {
reportSuccess();
return str;
});
可以说,映射函数应该用于映射,而不是副作用,因此即使它起作用,我也在寻找替代方法。
解决方法
结合在一起的peek
和peekLeft
与您要寻找的内容非常接近。
void reportFailure(RuntimeException e) {
System.out.println(e);
}
void reportSuccess(String value) {
System.out.println(value);
}
....
// prints: some value
Either<RuntimeException,String> right = Either.right("some value");
right.peekLeft(this::reportFailure).peek(this::reportSuccess);
// prints: java.lang.RuntimeException: some error
Either<RuntimeException,String> left = Either.left(
new RuntimeException("some error")
);
left.peekLeft(this::reportFailure).peek(this::reportSuccess);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。