Hello all, I need help coming up with a way to upd...
# getting-started
l
Hello all, I need help coming up with a way to update one of the existing MySection items in MyPost: Any help will be greatly appreciated data class MyPost( val somePostAttr: String, val rows: List<MyRow> ) data class MyRow( val someRowAttr: String, val columns: List<MyColumn> ) data class MyColumn( val someColumnAttr: String, val sections: List<MySection> ) data class MySection( val someSectionAttr: String )
s
Can you elaborate a bit? Since your properties are all immutable, any “update” would mean creating a new instance of
MyPost
. My first thought is that a simple solution would involve several nested calls to
copy
. If you want something a bit smarter you could look at #arrow Optics.
l
Yeah I will need to create a copy of MyPost and can’t seem to get the code right to do that
The starting point is fun MyPost.update(section: MySection): MyPost
s
How will you determine which section should be updated? Is the new section just appended to the column, or does it replace one of the existing sections?
l
Replace. Forgot to add a property id: String to MySection in the code above
s
👍
Here’s my version:
Copy code
val newPost = post.copy(
    rows = post.rows.map { row ->
        row.copy(columns = row.columns.map { column ->
            column.copy(sections = column.sections.map { oldSection ->  
                if (oldSection.id == newSection.id) newSection else oldSection
            })
        })
    }
)
So much nesting 😬 😄
I guess it would be possible to make a more efficient version that doesn’t copy the rows or columns that don’t contain the target section
l
Thank you so much Sam! It’s so simple now that I am looking at it :) really appreciate it. Have a great day
🐕 1