Android Kotlin adding additional field with value to data class

I have next data class in my app:

data class CarouselItem(
val url: String,
val pictureId: String,
val visible: String,
val id : String = UUID.randomUUID().toString()
) 

I get from the backend list of CarouselItems. They contain the first 3 fields (url, pictureId and visible). I want to additionally add field id to all created objects and add random unique id value to them. (would like to avoid wrapping this class with another one)

I expected this code to work, but instead, the id is not generated. I also tried adding it like this:

    data class CarouselItem(
    val url: String,
    val pictureId: String,
    val visible: String
) {
    val id: String = UUID.randomUUID().toString()
}

but it did not help. The id field is still null. To solve this, I added in the code for loop to go through the list and add these values.

I am curious, why is this not working. And is there any way to add these values in the data class? It looks much cleaner like that IMO. Thanks


You will often find occasions when you need to add, remove, manipulate fields in items you get from an api in order to make them fit the needs of an app. I find that it helps to have different classes to represent local and API data. That way you can make changes to one without necessarily affecting the other.

Using this approach you could have 2 data classes

data class ApiCarouselItem(
val url: String,
val pictureId: String,
val visible: String)

data class LocalCarouselItem(
val id: String,
val url: String,
val pictureId: String,
val visible: String)

The when you receive your api data it's a simple task to map from one to the other

val apiItems = // list of your items from the api
val localItems = apiItems.map{ apiItem -> 
    LocalApiItem(
    id = UUID.randomUUID().toString(),
    // assign url, pictureId, visible
    )    
}