gpt4 book ai didi

java - 为什么Java没有Try Monad?

转载 作者:行者123 更新时间:2023-12-01 19:56:17 30 4
gpt4 key购买 nike

我认为Java 8和更高版本(实际上是9和10)缺少有效地使用Stream和其他monad的功能。 Java没有任何类型的Try monad来处理monad编写期间的错误。

为什么?最初,我认为这只是缺少版本8,但我找不到在JDK中引入它的JEP

类似以下内容可能是一个起点。

public class Try<T> {
private T value;
private Exception exception;

private Try(Supplier<T> supplier) {
try {
this.value = supplier.get();
} catch (Exception ) {
this.exception = ex;
}
}

Optional<T> toOptional() {
return Optional.ofNullable(value);
}

public static <T> Try<T> of(Supplier<T> supplier) {
return new Try<>(supplier);
}
// Some other interesting methods...
}


也许不是任何人都使用响应流,但是在流转换期间,您需要一些聪明的方法来收集异常,而又不破坏整个流的执行。

stream
.map(info -> {
// Code that can rise an exception
// Without the Try monad is tedious to handle exceptions!
})
.filter(/* something */)
.to(/* somewhere */)


谁能解释我为什么?是否与其他一些规范缺乏相关?

谢谢大家。

最佳答案

在尝试情况下,它将用于替换以下代码:

int result;
try {
result = otherMethod();
} catch(exception ex) {
result = 0;
}


与:

result = Try.of(()->otherMethod()).orElse(0);


它较短,但是上面的代码是“ Pokemon Exception Handling”反模式的示例。忽略异常不是您想要在代码中执行的操作,简化操作也不是一个好主意。

没有技术原因没有 Try。包括VAVR等第三方功能编程库。将功能元素移植到Java时存在一些问题:不支持元组,不支持基元的泛型,已检查的异常。

关于java - 为什么Java没有Try Monad?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49646637/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com