https://kotlinlang.org logo
#getting-started
Title
# getting-started
c

Colton Idle

08/23/2022, 7:35 AM
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

Sam

08/23/2022, 7:39 AM
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

Colton Idle

08/23/2022, 7:54 AM
Oh. I like the helper function. Seems like I could use it all over the place. thanks!
🐕 1
r

Rob Elliot

08/23/2022, 9:20 AM
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

August Lilleaas

08/23/2022, 11:01 AM
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
3 Views