英文:
Consume both "left" and "right" of Vavr Either?
问题
如何以函数式的方式同时消费vavr中的“left”或“right”Either?
我有一个返回Either<RuntimeException, String>
的方法。基于这个结果,我需要执行一个回调到我们的报告库,例如reportSuccess()
或reportFailure()
。因此,我正在寻找一种优雅的函数式方法来实现这一点。如果Either
有一个biConsumer(Consumer<? super L> leftConsumer, Consumer<? super R> rightConsumer)
方法,我可以写出类似以下的代码:
Either<RuntimeException, String> result = // 从某处获取结果
result.biConsumer(ex -> {
reportFailure();
}, str -> {
reportSuccess();
});
到目前为止,我找到的最接近的解决方法是使用biMap()方法,代码类似于:
Either<RuntimeException, String> mappedResult = result.bimap(ex -> {
reportFailure();
return ex;
}, str -> {
reportSuccess();
return str;
});
可以说,映射函数应该用于映射而不是副作用,所以即使它能工作,我还在寻找其他的解决方法。
英文:
How can I consume both a "left" or a "right" of a vavr Either in a functional way?
I have a method that returns an Either<RuntimeException, String>
. Based on this result, I need to execute a callback to our reporting library, e.g. reportSuccess()
or reportFailure()
. Consequently, I am looking for a nice, functional way of doing it. If an Either
had a biConsumer(Consumer<? super L> leftConsumer, Consumer<? super R> rightConsumer
, I could write something like:
Either<RuntimeException, String> result = // get the result from somewhere
result.biConsumer(ex -> {
reportFailure();
}, str -> {
repportSuccess();
});
The closest workaround I have found so far is the biMap() method, which would look something like
Either<RuntimeException, String> mappedResult = result.bimap(ex -> {
reportFailure();
return ex;
}, str -> {
reportSuccess();
return str;
});
Arguably, mapping functions should be used for mapping and not side effects, so even if it works I am looking for alternatives.
答案1
得分: 3
有peek
和peekLeft
,结合使用,非常接近您所寻找的内容。
void reportFailure(RuntimeException e) {
System.out.println(e);
}
void reportSuccess(String value) {
System.out.println(value);
}
....
// 输出:some value
Either<RuntimeException, String> right = Either.right("some value");
right.peekLeft(this::reportFailure).peek(this::reportSuccess);
// 输出:java.lang.RuntimeException: some error
Either<RuntimeException, String> left = Either.left(
new RuntimeException("some error")
);
left.peekLeft(this::reportFailure).peek(this::reportSuccess);
英文:
There's peek
and peekLeft
that – in combination – are pretty close to what you are looking for.
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);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论