背景
我有一个可以返回的小函数Either<String, Float>
。如果成功,则返回浮点数,否则返回错误字符串。
我的目标是在管道中执行一系列操作,并使用 Either 实现面向铁路的编程。
代码
import java.util.function.Function;
import io.vavr.control.Either;
@Test
public void run(){
Function<Float, Either<String, Float>> either_double = num -> {
if(num == 4.0f)
Either.left("I don't like this number");
return Either.right(num * 2);
};
Function<Float, Float> incr = x -> x + 1.0f;
Float actual =
Either.right(2f)
.map(incr)
.map(either_double)
.get();
Float expected = 6.0f;
assertEquals(expected, actual);
}
这段代码做了一系列简单的操作。首先,我创建一个值为 2 的任意一个,然后将其递增,最后将其翻倍。这些操作的结果是 6。
问题
数学运算的结果是 6.0f,但这不是我得到的。相反,我得到Right(6.0f)
.
这是一个阻止代码编译的问题。我在 Either Monad 中有一个值,但是在检查了Either 的 API之后,我没有找到将其拆箱并按原样获取值的方法。
我考虑过使用getOrElseGet
,但即使该方法也返回一个 Right。
问题
如何访问存储在 Either Monad 中的实际值?