Is there a better way to "toggle" an item in a collection? I usually do something along the lines of (pseudo)
if(contains) remove else add
but feel dirty everytime.
k
Klitos Kyriacou
08/10/2022, 10:56 AM
If the collection is a
MutableSet
, you can do
set.add(item) || set.remove(item)
. Not sure how readable that is, though.
z
Zoltan Demant
08/10/2022, 11:01 AM
Thanks @Klitos Kyriacou, thats an approach I havent considered. I think Ill struggle understanding what it does if I come back to it at a later time 🥲
a
Ayfri
08/10/2022, 11:07 AM
Just create a simple extension like
Copy code
fun <T> MutableCollection<T>.toggle(property: T) {
if (property in this) remove(property) else add(property)
}
fun main() {
val myList = mutableListOf(1, 2, 3, 4)
myList.toggle(3)
myList.toggle(7)
println(myList)
}
// which prints :
// [1, 2, 4, 7]
z
Zoltan Demant
08/10/2022, 11:12 AM
@Ayfri If all else fails, thats what Ill do 👍🏽 I was sort of hoping that something like this was already available. Ive been reluctant to creating an extension function due to the fact that Im using this in a set of different modules, so Id need to create a module with this .. homer disappear
a
Ayfri
08/10/2022, 11:13 AM
yes you could even create a library with a set of useful extensions like this that you use in every projects you need it :)