Hey there. I got a situation where I must filter o...
# announcements
d
Hey there. I got a situation where I must filter out some items from a read only list which represents property of an object. A more visual representation of the nested classes would be like this:
Copy code
data class DataSourceResponse(val response: Response)
data class Response(val notifications: List<Notification>)
data class Notification(id: Int)
I have a function which takes a DataSourceResponse as a param and a callback, which should return a modified DataSourceResponse, filtering out some of the notifications from it. How should I implement this filtering and copy, considering the given model classes above. (immutable notifications list). The closest I got, was doing something like this:
Copy code
callback.onDataLoaded(
    paramDataSourceResponse.copy (
        response = paramDataSourceResponse.response.copy (
            notifications = paramDataSourceResponse.response.notifications.filter { check(it) }
        )
    )
)
but it looks kinda ugly to me. Also, not having every class made data class, would make it even uglier. Are there any other solutions for this?
h
👌 1
Thank you. I'm not sure I understand – how can the inner
Response
be a copy of the
paramDataSourceResponse
as well?
p
If you don’t have any other properties in your data classes then this should be fine:
Copy code
DataSourceResponse(Response(paramDataSourceResponse.response.notifications.filter { check(it) }))
d
@Pavlo Liapota yeah.. I have many other properties.. that was just to showcase the situation.
@hho DataSourceResponse is a wrapper class over Response, having some other properties as well
p
he means you have a type in your code example you should have
paramDataSourceResponse.response.copy (
instead of
paramDataSourceResponse.copy (
in your second
copy()
call
h
@Doru N. I think you were missing a
.response
in your inner copy.
Best I can come up with is going explicit:
Copy code
val filteredNotifications = paramDataSourceResponse.response.notifications.filter { check(it) }
val filteredResponse = paramDataSourceResponse.response.copy(notifications = filteredNotifications)
val filteredDataSourceResponse = paramDataSourceResponse.copy(response = filteredResponse)
callback.onDataLoaded(filteredDataSourceResponse)
p
Or maybe you can use
run
or
let
functions:
Copy code
paramDataSourceResponse.run {
    copy(response = response.run {
        copy(notifications = notifications.filter { check(it) })
    })
}
d
@hho oh, ok, didn’t see that
@Pavlo Liapota appreciate your opinions, but I think using those functions are useless, when you only have a
copy
function call inside