我有这段代码
Optional.ofNullable(user.getPhoneContact())
.ifPresent(phoneContact -> {
if (!PhoneUtils.isValid(phoneContact)) {
return new Exception();
}
}
.orElseThrow(() -> {
return new Exception();
}));
但是我有这个编译错误:
Required type: PhoneNumber
Provided: <lambda parameter>
错误在这里:
Optional.ofNullable(user.getPhoneContact())
.ifPresent(phoneContact -> {
if (!PhoneUtils.isValid(phoneContact)) {
return new Exception();
}
}
.orElseThrow(() -> { // this is inside of the lambda
return new Exception();
}));
您不能链接ifPresent和orElseThrow,因为ifPresent不会返回任何内容。
我的版本:
PhoneNumber phoneContact = Optional.ofNullable(user.getPhoneContact())
.orElseThrow(() -> {
return new Exception();
});
// if the phoneContact is null it will throw an exception in the previous lines
if (!PhoneUtils.isValid(phoneContact)) {
return new Exception();
}
您应该这样做
PhoneNumber phoneContact = Optional.ofNullable(user.getPhoneContact())
.orElseThrow(() -> new Exception("Phone number null!")
if(!PhoneUtils.isValid(phoneContact ))
throw new Exception("Phone number not valid!");