Is there a better way to write this? ```state.myL...
# getting-started
c
Is there a better way to write this?
Copy code
state.myList[index] = state.myList[index].copy(isFollowing = !state.myList[index].isFollowing!!)
A lot of ceremony just to flip the value of
isFollowing
s
Might be overkill, but if you have a lot of use cases like this you could look at #arrow optics
There’s also https://youtrack.jetbrains.com/issue/KT-44653 for the proposed “copy var” syntax but it’s gone a bit quiet, and I also don’t know if it would support your use case of indexing into a list
As far as the current language capabilities, the best I can think of is to use a helper function something like this:
Copy code
fun <T> MutableList<T>.update(i: Int, f: (T) -> T) {
    this[i] = f(this[i])
}
Then you can write
Copy code
state.myList.update(index) {
    it.copy(isFollowing = !it.isFollowing!!)
}
👍 5
c
Oh. I like the helper function. Seems like I could use it all over the place. thanks!
🐕 1
r
Could also add a helper function to the type of
state.myList[index]
to flip the status of `isFollowing`:
Copy code
fun MyType.toggleFollowing() = copy(isFollowing = !isFollowing)
Then it's:
Copy code
state.myList.update(1) { it.toggleFollowing() }
👌 3
a
I have my fingers crossed for “update” on lists and maps as a part of the standard library 😄 I use those functions in Clojure all the time
💯 1