在Java 8中尝试monad

Jir*_*ser 15 monads java-8

是否有内置的monad支持处理异常处理?类似于Scala的尝试.我问,因为我不喜欢未经检查的例外.

Joh*_*ean 15

通常至少有两个(例如在Maven Central上) - VavrCyclops都有Try实现,采用略有不同的方法.

Vavr的尝试非常密切地遵循Scala的尝试.它将捕获在执行组合器期间抛出的所有"非致命"异常.

Cyclops Try只会捕获显式配置的异常(当然,默认情况下,它也可以捕获所有内容),默认的操作模式只是在初始填充方法中捕获.这背后的原因是Try的行为方式与Optional相似 - Optional不会封装意外的Null值(即错误),只是我们合理预期没有值的地方.

以下是使用独眼巨人试用资源的示例

 Try t2 = Try.catchExceptions(FileNotFoundException.class,IOException.class)
               .init(()->PowerTuples.tuple(new BufferedReader(new FileReader("file.txt")),new FileReader("hello")))
               .tryWithResources(this::read2);
Run Code Online (Sandbox Code Playgroud)

另一个示例是"提升"现有方法(可能除以零)以支持错误处理.

    import static org.hamcrest.Matchers.equalTo;
    import static org.junit.Assert.*;
    import static com.aol.cyclops.lambda.api.AsAnyM.anyM;
    import lombok.val;

    val divide = Monads.liftM2(this::divide);

    AnyM<Integer> result = divide.apply(anyM(Try.of(2, ArithmeticException.class)), anyM(Try.of(0)));

    assertThat(result.<Try<Integer,ArithmeticException>>unwrapMonad().isFailure(),equalTo(true));
 private Integer divide(Integer a, Integer b){
    return a/b;
 }
Run Code Online (Sandbox Code Playgroud)


lba*_*scs 13

GitHub上的"better-java-monads"项目在这里有一个针对Java 8的Try monad .