Try monad in Java 8

后端 未结 6 2067
甜味超标
甜味超标 2020-12-30 04:15

Is there a built-in support for monad that deals with exception handling? Something similar to Scala\'s Try. I am asking because I don\'t like unchecked exceptions.

6条回答
  •  遥遥无期
    2020-12-30 04:56

    You can do what you want by (ab)using CompletableFuture. Please don't do this in any sort of production code.

    CompletableFuture sc = CompletableFuture.completedFuture(
                                                          new Scanner(System.in));
    
    CompletableFuture divident = sc.thenApply(Scanner::nextInt);
    CompletableFuture divisor = sc.thenApply(Scanner::nextInt);
    
    CompletableFuture result = divident.thenCombine(divisor, (a,b) -> a/b);
    
    result.whenComplete((val, ex) -> {
        if (ex == null) {
            System.out.printf("%s/%s = %s%n", divident.join(), divisor.join(), val);
        } else {
            System.out.println("Something went wrong");
        }
    });
    

提交回复
热议问题