如何将一个字符串分配给另一个数据class成员的字符串?

How to assign a string to another string of a data class member?

我正在尝试将字符串值分配给数据 class 对象的字符串属性部分,但它不起作用:

appointmentInfo.mySymptoms?.medsDescription = "string description"

其中,

data class AppointmentInfo(var id : Int? = null,
                           var planType : String? = null,
                           var dateFormat : DateFormat,
                           var mySymptoms : MySymptoms? = null) : Parcelable

@Parcelize
data class MySymptoms(var grantAccess : Boolean,
                      var takingMeds : Boolean,
                      var medsDescription : String? = null,
                      var symptomList : List<String>? = null,
                      var symptomsDescription : String? = null,
                      var generalDescription : String? = null ```

**appointmentInfo.mySymptoms?.medsDescription is always null**

确保变量分配正确。

代码

data class AppointmentInfo(
    var mySymptoms : MySymptoms? = null,
)

data class MySymptoms(
    var medsDescription : String? = null,
)
                      
fun main() {
    var appointmentInfo = AppointmentInfo()
    appointmentInfo.mySymptoms = MySymptoms()
    appointmentInfo.mySymptoms?.medsDescription = "string description"
    println(appointmentInfo.mySymptoms?.medsDescription)
}

输出

string description

Kotlin Playground link

您应该使用数据 class https://kotlinlang.org/docs/data-classes.html#copyingcopy() 函数,因为 Jet Brains 建议所有数据 class 成员应该是只读的 val