You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot Kotlin项目lambda内赋值报Assignments are not expressions错求助

Kotlin lambda内赋值报错解决方案

错误原因

  • Kotlin语法规则要求:赋值操作=不属于表达式,无返回值。你在forEach的lambda代码块中用括号包裹赋值语句,会让Kotlin将该赋值语句识别为lambda的返回值,但forEach要求lambda返回Unit类型,因此触发语法报错
  • 代码中冗余的括号是直接诱因

修复方法

删除所有多余的括号,调整后的代码如下:

patientDto.forEach { patient ->
    patient.problems.forEach { problem ->
        problem.problemId = patient.patientId
    }
}

额外逻辑修正建议

你当前findAll方法中存在逻辑错误:直接将List<Patient>集合整体映射为单个ReqPatient对象,再封装为单元素列表返回,无法返回所有患者数据,建议调整为如下写法:

@Throws(Exception::class)
fun findAll():List<ReqPatient>{
    try {
        val patientList : List<Patient?>? = patientRepository.findAllByStatusEquelsOne()
        if (patientList.isNullOrEmpty()){
            logger.error("无可用患者记录")
            throw PatientNotFoundException()
        }
        // 逐个转换实体为DTO
        val patientDtoList: List<ReqPatient> = patientList.filterNotNull().map { patient ->
            modelMapper.map(patient, ReqPatient::class.java)
        }
        // 批量赋值problemId
        patientDtoList.forEach { patient ->
            patient.problems.forEach { problem ->
                problem.problemId = patient.patientId
            }
        }
        return patientDtoList
    }catch (e:Exception){
        throw Exception(e)
    }
}

内容的提问来源于stack exchange,提问作者Mama

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 11:48:03