So, I have a bunch of data immutable classes that ...
# getting-started
s
So, I have a bunch of data immutable classes that make up a nested structure (represeting a GraphQL response) and I'd like to mutate one of the nested values to get an immutable copy. for example:
Copy code
data class User(val name: String, val location: Location)
data class Location(val city: City, val somethingElse: String) // for example
data class City(val name: String, val country: String)
I have a user and I want to change the city name, getting a copy of user with everything else on the chain unchanged. I can do it with copy:
Copy code
val newUser = user.copy(location = user.location.copy(city = user.location.city.copy(name = "New name")))
but that's far too long esentially I'd like to be able to do something shorter like:
Copy code
val newUser = user.copy { it.location.city.name = "New name" }
I don't think the above could get gotten to work, but is there something in those lines I can do? (also, not my actual data structure, but sufficient for this example) Thanks 🙂
r
There is concept called "Lenses" which targets the general problem of updating nested immutable data. The arrow library for example provides structures to achieve just that: https://arrow-kt.io/docs/optics/lens/ And it will also generate the boilerplate for you.
s
thanks. I found that, but was hoping to do without boilerplate and an extra library, though
swift handles this fairly nicely and js at the very least has immutability-helper that's quite useful. was hoping for somethign simpler
r
I'm not aware of a simpler/more elagant solution, I'm sorry
s
thanks though
r
You're welcome. :)