这是我的代码:

var header1: Record? = null
var header2: Record? = null

header2 = header1
header2.name = "new_name"

but header1.name changes too!

推荐答案

You are just assigning the same object (same chunk of memory) to another variable. You need to somehow create a new instance and set all fields.

header2 = Record()
header2.name = header1.name

However in Kotlin, if the Record class was Data class, Kotlin would create a copy method for you.

data class Record(val name: String, ...)
...
header2 = header1.copy()

复制方法允许您覆盖需要覆盖的字段.

header2 = header1.copy(name = "new_name")

Kotlin相关问答推荐

Spring Boot Bean验证器未触发

Scala与Kotlin中的迭代

Kotlin Coroutine()是如何工作的?S阻止了.

如何让 LocalDateTime.parse 拒绝 24:00 时间

collectAsState 未从存储库接收更改

如何从 Period.between() 返回的字符串中提取信息? (Kotlin )

在 Kotlin 中 import 如何找到文件路径?

将 Kotlin 类属性设置器作为函数引用

`this@classname` 在 Kotlin 中是什么意思?

在粘贴时将 java 转换为 kotlin

使用kotlinx协同程序测试中的类时出错

在java代码中使用kotlin库

面临一些未知问题一些后端jvm内部错误

Kotlin val difference getter override vs assignment

在 gradle android library kotlin 项目中禁用 META-INF/* 生成

如何在Android Studio 4.1中默认启用Kotlin Android扩展

无法解决:androidx.lifecycle:lifecycle-extensions-ktx:2.0.0-alpha1

Gradle:无法连接到 Windows 上的 Kotlin 守护程序

安装 Kotlin-Jupyter:e: java.lang.NoClassDefFoundError: 无法初始化类 org.jetbrains.kotlin.com.intellij.pom.java.LanguageLevel

Kotlin扩展函数与成员函数?