gpt4 book ai didi

java - 泛型方法返回 'nothing'但不能返回null时返回什么?

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:13:11 24 4
gpt4 key购买 nike

假设我有一个这样的库方法(非常简短):

public static <V> Optional<V> doSomethingWith(Callable<V> callable) {
try {
return Optional.of(callable.call());
} catch (Exception ex) {
// Do something with ex
return Optional.empty();
}
}

我想要一些不返回值的东西,比如:

    Library.</*What1*/>doSomethingWith(() -> {
foo();
return /*what2*/;
});

对于不返回值的泛型方法,我的第一直觉是将类型设置为 Void 并返回 null,但是因为结果被包裹在 >可选 这会引发异常。

什么是 /*What1*//*what2*/ 的合理占位符,它们看起来不像 Integer0?

[编辑]我试图避免 Optional.ofNullable,因为这里使用 empty 表示 callable.call() 没有正常完成。

最佳答案

如果您需要一个永远不会被使用的通用参数的类型提示,您可以使用 Void ,JDK 在某些情况下也会这样做,例如转换时 Runnable进入CompletableFuture<T>它对 T 使用 Void。

如果您使用 Optional.ofNullable那么你可以返回null对于 what2,这是 Void 的唯一有效值.

[edit] I'm trying to avoid Optional.ofNullable because empty is used here to indicate that callable.call() did not complete normally.

那么您使用的工具是错误的。 CompletionStageCompletableFuture具有正确的语义。

关于java - 泛型方法返回 'nothing'但不能返回null时返回什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41360520/

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