Kotlin 数据类的 copy() 值丢失

Nev*_*eps 0 kotlin

我有这样的data class

data class BookObject(
    val description: String?,

    val owningCompanyData: OwningCompanyData?,
) {
    var id: String? = null
    var createdAt: Instant? = null
    var createdBy: String? = null
    var modifiedAt: Instant? = null

    fun update(command: CreateOrUpdateBookObjectCommand): BookObject =
        this.copy(
            description = command.description,
            owningCompanyData = command.owningCompanyData
        )
}
Run Code Online (Sandbox Code Playgroud)

当我对update具有完全填充字段的对象使用该函数时,我得到一个具有空id, createdAt, createdBy,modifiedAt字段的对象(它们等于null)。但为什么会出现这种情况呢?为什么这些领域失去了它们的价值?

kotlin 文档说:

使用 copy() 函数复制对象,允许您更改其某些属性,同时保持其余属性不变

小智 5

答案实际上存在于您的链接中,位于“复制”之前的段落中。

编译器仅使用主构造函数中定义的属性来自动生成函数。