In my shared code I have this and would a contract...
# multiplatform
j
In my shared code I have this and would a contract make sense here to so I don't have to force unwrap or use the null checks where I call the add function? I am trying to understand where the contract keyword makes sense.
Copy code
fun addClothingToClothingWeather(clothing:ClothingTypes) {
        if(clothingWeatherData == null) clothingWeatherData = ClothingWeatherModel()
        clothingWeatherData!!.clothing?.toMutableList()?.add(clothing)
    }

@Serializable
data class ClothingWeatherModel(val clothing:List<ClothingTypes>? = emptyList(), val temperature:MainTemperature? = null, val situation:Situations? = null)
r
I don’t think a contract makes sense here. Why? Because you are working with mutable data. Some concurrent could actually modify your
clothingWeatherData
variable and possibly set it to
null
. So you can’t really guarantee that it isn’t
null
. FYI
toMutableList
actually makes a copy of your list, so the added
clothing
won’t be part of the original list in the
ClothingWeatherModel
. Something like the following would work:
Copy code
@Serializable
data class ClothingWeatherModel(
    val clothing:List<ClothingTypes>? = emptyList(),
    val temperature:MainTemperature? = null,
    val situation:Situations? = null
)

var clothingWeatherData: ClothingWeatherModel? = null

fun addClothingToClothingWeather(clothing:ClothingTypes) {
    val data = clothingWeatherData ?: ClothingWeatherModel()
    val list = data.clothing?.toMutableList()?.apply { add(clothing) } ?: listOf(clothing)
    clothingWeatherData = data.copy(clothing = list)
}
j
Thanks, I figured that out after I posted this that my list wasn't being put into the data class. I also decided to just initialize clothingWeatherData right away so it is always initialized.
👍🏻 1