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

SpringBoot+MongoDB项目Kotlin出现「赋值不是表达式」错误如何解决

问题原因及解决方案

1. 「Assignments are not expressions」报错修复

这个报错是因为你混淆了Java Builder链式调用的写法和Kotlin赋值语法,Builder的属性设置是方法调用,不能用=赋值,要改成括号传参的形式。
修正后的代码如下:

@PostMapping(value = ["/users"], produces = [MediaType.APPLICATION_JSON_VALUE])
fun createUser(@RequestBody payload: Signup): ResponseEntity<*>? {
    log.info("creating user {}", payload.username)
    val user: User = User
        .builder()
        .username(payload.username)
        .email(payload.email)
        .password(payload.password)
        .userProfile(
            Profile
                .builder()
                .displayName(payload.name)
                .profilePictureUrl(payload.profilePicUrl)
                .build()
        )
        .build()
    try {
        userService.registerUser(user, Role.USER)
    } catch (e: UserNameAlreadyExistException) {
        throw BadRequestException(e.message)
    } catch (e: EmailAlreadyExistException) {
        throw BadRequestException(e.message)
    }
    val location = ServletUriComponentsBuilder
        .fromCurrentContextPath().path("/users/{username}")
        .buildAndExpand(user.userName).toUri()
    return ResponseEntity
        .created(location)
        .body(ApiResponse(true, "User registered successfully"))
}

2. Builder 导包选择

你当前技术栈下Builder的生成有两种常用方案,根据你的实现选择对应导包:

  • 如果你用Lombok自动生成Builder:
    在User、Profile实体类上添加@Builder注解,对应的导包为lombok.Builder。额外注意需要同时给实体类添加@Document(MongoDB实体映射,导包org.springframework.data.mongodb.core.mapping.Document)、@Data、@NoArgsConstructor、@AllArgsConstructor注解,避免MongoDB序列化/反序列化报错。
  • 如果你不想用Lombok:
    Kotlin原生更推荐使用data类实现实体,不需要额外的Builder工具,直接用命名参数构造即可,写法更简洁:
    // 实体定义示例
    data class User(
        val username: String,
        val email: String,
        val password: String,
        val userProfile: Profile
    )
    data class Profile(
        val displayName: String,
        val profilePictureUrl: String
    )
    
    // 构造对象直接写
    val user = User(
        username = payload.username,
        email = payload.email,
        password = payload.password,
        userProfile = Profile(
            displayName = payload.name,
            profilePictureUrl = payload.profilePicUrl
        )
    )
    

内容的提问来源于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 19:27:02