这是使用和初始化Optional变量的正确方法吗。.当我调用calculateAnnualCalculationTotal时,在所有这些变量上都收到一个错误“变量可能未初始化”。如果保险,我想在AnnualCalculationSummaryDto中使用这些变量.product不是abc或def,否则试图在AnnualCalculationSummaryDto中设置的这三个字段应保持为null ..
Optional<CalculatedPaymentsDto> calculatedPayments ;
Optional<PaidPaymentsDTO> paidPayments ;
Optional<CreatePaymentResponseDto> payment ;
if (!insurance.getProduct().equalsIgnoreCase("abc") && !insurance.getProduct().equalsIgnoreCase("def")) {
int totalAnnualCalculationSum = calculateAnnualCalculationTotal(insurance, requestDto.getAnnualCalculationYear(), calculatedPayments, paidPayments);
payment = Optional.ofNullable(createPayment(getCreatePaymentRequestDto(insurance, calculatedPayments.get(), totalAnnualCalculationSum, requestDto.getAnnualCalculationYear())));
}
AnnualCalculationSummaryDto annualCalculationSummaryDto = new AnnualCalculationSummaryDto();
if(calculatedPayments.isPresent() && paidPayments.isPresent() && payment.isPresent()){
annualCalculationSummaryDto.setCalculatedPaymentsDto(calculatedPayments.get());
annualCalculationSummaryDto.setPaidPaymentsDTO(paidPayments.get());
annualCalculationSummaryDto.setPayments(payment.get());
}
annualCalculationSummaryDto.setParam1(inr.getProduct());
annualCalculationSummaryDto.setParam2(requestDto.getTotal());
annualCalculationSummaryRepository.save(annualCalculationSummaryDto);
........ ............. ..............
private int calculateAnnualCalculationTotal (Insurance insurance , int year , Optional<CalculatedPaymentsDto> calculatedPayments , Optional<PaidPaymentsDTO> paidPayments) {
calculatedPayments = Optional.ofNullable(paymentService.getCalculatedPayments(insurance.getId(), year));
paidPayments = Optional.ofNullable(paymentService.getPaidPayments(insurance.getInsuranceYears(), year));
totalSum = calculatedPayments.get().getParam1()+ paidPayments.get().getParam2();
.....
}
或者有更好的方法来写这个..
答案 0 :(得分:1)
付款是在if子句中初始化的,因此,不保证在if子句后使用它时会对其进行初始化。
要将Optional初始化为“ null”:Optional<T> myOptional = Optional.empty();
关于[Optionals]
的精彩文章