Is there a better way to "toggle" an item in a col...
# stdlib
z
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
If the collection is a
MutableSet
, you can do
set.add(item) || set.remove(item)
. Not sure how readable that is, though.
z
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
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
@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
yes you could even create a library with a set of useful extensions like this that you use in every projects you need it :)
👍🏽 1