Home > OS >  How to assign a string to another string of a data class member?
How to assign a string to another string of a data class member?

Time:05-21

I'm trying to assign a string value to an string attribute part of a data class object and it's not working:

appointmentInfo.mySymptoms?.medsDescription = "string description"

where,

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**

CodePudding user response:

Make sure the variables are assigned properly.

Code

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)
}

Output

string description

Kotlin Playground link

CodePudding user response:

You should use copy() function of data class https://kotlinlang.org/docs/data-classes.html#copying as Jet Brains suggests all data class member should be read only val

  • Related