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

Kotlin实体类次级构造器报There's a cycle in the delegation calls chain错误

报错原因

你遇到的There's a cycle in the delegation calls chain报错,核心是第一个次级构造器出现了自调用死循环:
你定义的三个参数的次级构造器,在委托调用this(userName,password,email)时,传入的三个String参数刚好匹配当前构造器本身的参数列表,相当于构造器自己调用自己,形成了无限循环的调用链,编译器直接拦截报错。
同时还有一个隐藏问题:你的主构造器中userProfile参数没有设置默认值,属于必填参数,任何次级构造器委托调用主构造器时,都必须传入该参数的有效值,否则也会编译失败。

修正方案

第一步:修复第一个构造器的调用逻辑

如果你的业务需要支持仅传入userName、password、email初始化User,建议先给主构造器的userProfile补充默认值,再调整第一个次级构造器的委托调用目标为主构造器,而非自身。

第二步:删除冗余赋值代码

第二个次级构造器已经通过this(...)把所有参数传递给主构造器完成了属性赋值,构造器体内的重复赋值逻辑完全冗余,可以直接删除。

修正后完整代码

package com.nilmani.mychat.model

import org.jetbrains.annotations.NotNull
import org.springframework.data.annotation.Id
import org.springframework.data.mongodb.core.mapping.Document
import java.time.LocalDate


@Document
open  class User(
    @Id
    var id: String ="",
    var userName:String="",
    private var password:String="",
    var email:String="",
    var createdAt:LocalDate=LocalDate.now(),
    var updatedAt:LocalDate= LocalDate.now(),
    var active:Boolean=false,
    // 补充userProfile的默认值,可根据业务调整初始化逻辑
    @NotNull
    var userProfile:Profile = Profile(),
    @NotNull
    var role:MutableSet<Role> = HashSet()
) {
    constructor(
                userName: String,
                password: String,
                email: String,
                // 如果不需要默认Profile,也可以在这里新增userProfile入参
                ) : this(userName = userName, password = password, email = email){
        // 已经通过主构造器赋值,这里不需要重复写赋值逻辑
    }
    constructor(user:User):
            this(user.id,user.userName,
                user.password,user.email,
                user.createdAt,user.updatedAt,
            user.active,user.userProfile,
            user.role)
            // 构造器体内重复赋值逻辑全部删除即可
}

如果你的业务不允许给userProfile设置全局默认值,就把第一个次级构造器调整为接收userProfile参数:

constructor(
    userName: String,
    password: String,
    email: String,
    userProfile: Profile
) : this(userName = userName, password = password, email = email, userProfile = userProfile)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 06:57:03