不存在类型变量 U 的实例,因此 void 符合 U
No instance(s) of type variable(s) U exist so that void conforms to U
我试图避免 isPresent
检查我下面的代码,但编译器发出错误消息
"No instance(s) of type variable(s) U
exist so that void
conforms to U
"
正在打电话给 printAndThrowException
。这是我的代码:
values.stream()
.filter(value -> getDetails(value).getName.equals("TestVal"))
.findFirst()
.map(value -> printAndThrowException(value))
.orElseThrow(new Exception2("xyz"));
有问题的 printAndThrowException 方法具有以下签名:
void printAndThrowException(Pojo value)
上述方法总是抛出RuntimeException
类型的异常。上面提到的代码不是确切的代码,只是转换了我的代码来表示情况。
这里有什么问题,调用printAndThrowException
时如何避免使用isPresent
?
Optional.map()
需要一个 Function<? super T, ? extends U>
作为参数。由于你的方法 returns void
,它不能在 lambda 中这样使用。
我在这里看到三个选项:
- 采用该方法 return
Void
/Object
/随便什么——语义上不理想但它会工作
- 使该方法 return 成为异常,并将 lambda 定义更改为
.map(v -> {
throw printAndReturnException();
});
- 使用
ifPresent()
,并将orElseThrow()
移出调用链:
values.stream()
.filter(value -> getDetails(value).getName.equals("TestVal"))
.findFirst()
.ifPresent(value -> printAndThrowException(value))
throw new Exception2("xyz");
我试图避免 isPresent
检查我下面的代码,但编译器发出错误消息
"No instance(s) of type variable(s)
U
exist so thatvoid
conforms toU
"
正在打电话给 printAndThrowException
。这是我的代码:
values.stream()
.filter(value -> getDetails(value).getName.equals("TestVal"))
.findFirst()
.map(value -> printAndThrowException(value))
.orElseThrow(new Exception2("xyz"));
有问题的 printAndThrowException 方法具有以下签名:
void printAndThrowException(Pojo value)
上述方法总是抛出RuntimeException
类型的异常。上面提到的代码不是确切的代码,只是转换了我的代码来表示情况。
这里有什么问题,调用printAndThrowException
时如何避免使用isPresent
?
Optional.map()
需要一个 Function<? super T, ? extends U>
作为参数。由于你的方法 returns void
,它不能在 lambda 中这样使用。
我在这里看到三个选项:
- 采用该方法 return
Void
/Object
/随便什么——语义上不理想但它会工作 - 使该方法 return 成为异常,并将 lambda 定义更改为
.map(v -> { throw printAndReturnException(); });
- 使用
ifPresent()
,并将orElseThrow()
移出调用链:values.stream() .filter(value -> getDetails(value).getName.equals("TestVal")) .findFirst() .ifPresent(value -> printAndThrowException(value)) throw new Exception2("xyz");