Java三元表达式void与String条件操作数类型不兼容解决方法
问题
需要将computeDto.getPharmacie().getMotiRefuse()的属性值设置为traitement en chevauchement non pris en charge ,编写代码后编译失败,抛出错误:Incompatible conditional operand types void and String!
原始代码如下:
Map result = new HashMap<String, Object>(); long dureeTrait=Long.parseLong(dureeTraitement); if(difference_In_Days > dureeTrait) { result.put("motifPharmacie", computeDto.getPharmacie().getMotiRefuse() != null ? computeDto.getPharmacie().getMotiRefuse(): ""); } else { result.put("motifPharmacie", computeDto.getPharmacie().getMotiRefuse() != null ? computeDto.getPharmacie().setMotiRefuse("traitement en chevauchement non pris en charge "): ""); }
报错根因
Java三元运算符要求:两侧的表达式返回值类型兼容,当前else分支中setMotiRefuse()是返回void的setter方法,和另一侧分支的String类型无法匹配,因此编译不通过。
修复方案
不要把无返回值的setter调用直接放在三元表达式的返回分支里,先完成赋值操作,再取属性值存入Map即可,同时可以提前提取关联对象减少重复方法调用:
Map<String, Object> result = new HashMap<>(); long dureeTrait = Long.parseLong(dureeTraitement); // 提前取出pharmacie对象,避免重复调用getPharmacie() // 若当前JDK版本不支持var,替换为对应Pharmacie类的显式类型声明即可 var pharmacie = computeDto.getPharmacie(); if (difference_In_Days > dureeTrait) { String existMotif = pharmacie.getMotiRefuse() != null ? pharmacie.getMotiRefuse() : ""; result.put("motifPharmacie", existMotif); } else { // 先执行setter完成属性赋值 pharmacie.setMotiRefuse("traitement en chevauchement non pris en charge "); // 再取赋值后的值存入Map String currentMotif = pharmacie.getMotiRefuse() != null ? pharmacie.getMotiRefuse() : ""; result.put("motifPharmacie", currentMotif); }
内容的提问来源于stack exchange,提问作者drn123
相关产品推荐
相关产品推荐

